]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Add support for opening a MeshLink instance without permanent storage.
[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                 config_t config = {data, len};
562                 node_t *n = new_node();
563
564                 if(!node_read_from_config(mesh, n, &config)) {
565                         free_node(n);
566                         logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
567                         meshlink_errno = MESHLINK_EPEER;
568                         return false;
569                 }
570
571                 if(!strcmp(n->name, name)) {
572                         logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
573                         free_node(n);
574                         meshlink_errno = MESHLINK_EPEER;
575                         return false;
576                 }
577
578                 node_add(mesh, n);
579
580                 if(!config_write(mesh, n->name, &config)) {
581                         return false;
582                 }
583         }
584
585         sptps_send_record(&(mesh->sptps), 1, ecdsa_get_public_key(mesh->private_key), 32);
586
587         free(mesh->name);
588         free(mesh->self->name);
589         mesh->name = xstrdup(name);
590         mesh->self->name = xstrdup(name);
591
592         logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
593
594         return true;
595 }
596
597 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
598         (void)type;
599         meshlink_handle_t *mesh = handle;
600         const char *ptr = data;
601
602         while(len) {
603                 int result = send(mesh->sock, ptr, len, 0);
604
605                 if(result == -1 && errno == EINTR) {
606                         continue;
607                 } else if(result <= 0) {
608                         return false;
609                 }
610
611                 ptr += result;
612                 len -= result;
613         }
614
615         return true;
616 }
617
618 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
619         meshlink_handle_t *mesh = handle;
620
621         switch(type) {
622         case SPTPS_HANDSHAKE:
623                 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
624
625         case 0:
626                 return finalize_join(mesh, msg, len);
627
628         case 1:
629                 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
630                 shutdown(mesh->sock, SHUT_RDWR);
631                 mesh->success = true;
632                 break;
633
634         default:
635                 return false;
636         }
637
638         return true;
639 }
640
641 static bool recvline(meshlink_handle_t *mesh, size_t len) {
642         char *newline = NULL;
643
644         if(!mesh->sock) {
645                 abort();
646         }
647
648         while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
649                 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
650
651                 if(result == -1 && errno == EINTR) {
652                         continue;
653                 } else if(result <= 0) {
654                         return false;
655                 }
656
657                 mesh->blen += result;
658         }
659
660         if((size_t)(newline - mesh->buffer) >= len) {
661                 return false;
662         }
663
664         len = newline - mesh->buffer;
665
666         memcpy(mesh->line, mesh->buffer, len);
667         mesh->line[len] = 0;
668         memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
669         mesh->blen -= len + 1;
670
671         return true;
672 }
673 static bool sendline(int fd, char *format, ...) {
674         static char buffer[4096];
675         char *p = buffer;
676         int blen = 0;
677         va_list ap;
678
679         va_start(ap, format);
680         blen = vsnprintf(buffer, sizeof(buffer), format, ap);
681         va_end(ap);
682
683         if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
684                 return false;
685         }
686
687         buffer[blen] = '\n';
688         blen++;
689
690         while(blen) {
691                 int result = send(fd, p, blen, MSG_NOSIGNAL);
692
693                 if(result == -1 && errno == EINTR) {
694                         continue;
695                 } else if(result <= 0) {
696                         return false;
697                 }
698
699                 p += result;
700                 blen -= result;
701         }
702
703         return true;
704 }
705
706 static const char *errstr[] = {
707         [MESHLINK_OK] = "No error",
708         [MESHLINK_EINVAL] = "Invalid argument",
709         [MESHLINK_ENOMEM] = "Out of memory",
710         [MESHLINK_ENOENT] = "No such node",
711         [MESHLINK_EEXIST] = "Node already exists",
712         [MESHLINK_EINTERNAL] = "Internal error",
713         [MESHLINK_ERESOLV] = "Could not resolve hostname",
714         [MESHLINK_ESTORAGE] = "Storage error",
715         [MESHLINK_ENETWORK] = "Network error",
716         [MESHLINK_EPEER] = "Error communicating with peer",
717         [MESHLINK_ENOTSUP] = "Operation not supported",
718         [MESHLINK_EBUSY] = "MeshLink instance already in use",
719 };
720
721 const char *meshlink_strerror(meshlink_errno_t err) {
722         if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
723                 return "Invalid error code";
724         }
725
726         return errstr[err];
727 }
728
729 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
730         logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
731
732         mesh->private_key = ecdsa_generate();
733         mesh->invitation_key = ecdsa_generate();
734
735         if(!mesh->private_key || !mesh->invitation_key) {
736                 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
737                 meshlink_errno = MESHLINK_EINTERNAL;
738                 return false;
739         }
740
741         logger(mesh, MESHLINK_DEBUG, "Done.\n");
742
743         return true;
744 }
745
746 static struct timeval idle(event_loop_t *loop, void *data) {
747         (void)loop;
748         meshlink_handle_t *mesh = data;
749         struct timeval t, tmin = {3600, 0};
750
751         for splay_each(node_t, n, mesh->nodes) {
752                 if(!n->utcp) {
753                         continue;
754                 }
755
756                 t = utcp_timeout(n->utcp);
757
758                 if(timercmp(&t, &tmin, <)) {
759                         tmin = t;
760                 }
761         }
762
763         return tmin;
764 }
765
766 // Get our local address(es) by simulating connecting to an Internet host.
767 static void add_local_addresses(meshlink_handle_t *mesh) {
768         struct sockaddr_storage sn;
769         socklen_t sl = sizeof(sn);
770
771         // IPv4 example.org
772
773         if(getlocaladdr("93.184.216.34", (struct sockaddr *)&sn, &sl)) {
774                 ((struct sockaddr_in *)&sn)->sin_port = ntohs(atoi(mesh->myport));
775                 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
776         }
777
778         // IPv6 example.org
779
780         sl = sizeof(sn);
781
782         if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", (struct sockaddr *)&sn, &sl)) {
783                 ((struct sockaddr_in6 *)&sn)->sin6_port = ntohs(atoi(mesh->myport));
784                 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
785         }
786 }
787
788 #if 0
789 static bool meshlink_write_config(meshlink_handle_t *mesh) {
790         uint8_t buf[1024];
791         packmsg_output_t out = {buf, sizeof buf};
792         packmsg_add_str(&out, mesh->name);
793         packmsg_add_uint32(&out, mesh->devclass);
794         packmsg_add_uint16(&out, mesh->port);
795         packmsg_add_bin(&out, ecdsa, sizeof(ecdsa));
796         uint32_t len = packmsg_output_size(&out, buf);
797
798         if(!len) {
799                 logger(mesh, MESHLINK_DEBUG, "Could not create configuration data\n",);
800                 meshlink_errno = MESHLINK_EINTERNAL;
801                 return false;
802         }
803 }
804 #endif
805
806 static bool meshlink_setup(meshlink_handle_t *mesh) {
807         if(!config_init(mesh)) {
808                 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s: %s\n", mesh->confbase, strerror(errno));
809                 meshlink_errno = MESHLINK_ESTORAGE;
810                 return false;
811         }
812
813         if(!ecdsa_keygen(mesh)) {
814                 meshlink_errno = MESHLINK_EINTERNAL;
815                 return false;
816         }
817
818         if(check_port(mesh) == 0) {
819                 meshlink_errno = MESHLINK_ENETWORK;
820                 return false;
821         }
822
823         /* Create a node for ourself */
824
825         mesh->self = new_node();
826         mesh->self->name = xstrdup(mesh->name);
827         mesh->self->devclass = mesh->devclass;
828         mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
829
830         // Write the main config file
831         uint8_t buf[4096];
832         packmsg_output_t out = {buf, sizeof(buf)};
833
834         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
835         packmsg_add_str(&out, mesh->name);
836         packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
837         packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
838         packmsg_add_uint16(&out, atoi(mesh->myport));
839
840         config_t config = {buf, packmsg_output_size(&out, buf)};
841
842         if(!main_config_write(mesh, &config)) {
843                 return false;
844         }
845
846         // Write our own host config file
847         out.ptr = buf;
848         out.len = sizeof(buf);
849         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
850         packmsg_add_str(&out, mesh->name);
851         packmsg_add_int32(&out, mesh->devclass);
852         packmsg_add_bool(&out, false);
853         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
854         packmsg_add_str(&out, ""); // TODO: copy existing canonical address, in case it was added before meshlink_join().
855         packmsg_add_array(&out, 0);
856
857         config.len = packmsg_output_size(&out, buf);
858
859         if(!config_write(mesh, mesh->name, &config)) {
860                 return false;
861         }
862
863         return true;
864 }
865
866 static bool meshlink_read_config(meshlink_handle_t *mesh) {
867         // Open the configuration file and lock it
868         if(!main_config_lock(mesh)) {
869                 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
870                 meshlink_errno = MESHLINK_ESTORAGE;
871                 return false;
872         }
873
874         config_t config;
875
876         if(!main_config_read(mesh, &config)) {
877                 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
878                 return false;
879         }
880
881         packmsg_input_t in = {config.buf, config.len};
882         const void *private_key;
883         const void *invitation_key;
884
885         uint32_t version = packmsg_get_uint32(&in);
886         char *name = packmsg_get_str_dup(&in);
887         uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
888         uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
889         uint16_t myport = packmsg_get_uint16(&in);
890
891         if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
892                 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
893                 free(name);
894                 config_free(&config);
895                 return false;
896         }
897
898 #if 0
899
900         // TODO: check this?
901         if(mesh->name && strcmp(mesh->name, name)) {
902                 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
903                 meshlink_errno = MESHLINK_ESTORAGE;
904                 free(name);
905                 config_free(&config);
906                 return false;
907         }
908
909 #endif
910
911         free(mesh->name);
912         mesh->name = name;
913         xasprintf(&mesh->myport, "%u", myport);
914         mesh->private_key = ecdsa_set_private_key(private_key);
915         mesh->invitation_key = ecdsa_set_private_key(invitation_key);
916         config_free(&config);
917
918         /* Create a node for ourself and read our host configuration file */
919
920         mesh->self = new_node();
921         mesh->self->name = xstrdup(name);
922         mesh->self->devclass = mesh->devclass;
923
924         if(!node_read_public_key(mesh, mesh->self)) {
925                 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
926                 free_node(mesh->self);
927                 mesh->self = NULL;
928                 return false;
929         }
930
931         return true;
932 }
933
934
935 static meshlink_handle_t *meshlink_open_internal(const char *confbase, const char *name, const char *appname, dev_class_t devclass, const void *key, size_t keylen) {
936         // Validate arguments provided by the application
937         bool usingname = false;
938
939         if(!appname || !*appname) {
940                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
941                 meshlink_errno = MESHLINK_EINVAL;
942                 return NULL;
943         }
944
945         if(strchr(appname, ' ')) {
946                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
947                 meshlink_errno = MESHLINK_EINVAL;
948                 return NULL;
949         }
950
951         if(name) {
952                 if(!check_id(name)) {
953                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
954                         meshlink_errno = MESHLINK_EINVAL;
955                         return NULL;
956                 }
957
958                 usingname = true;
959         }
960
961         if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
962                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
963                 meshlink_errno = MESHLINK_EINVAL;
964                 return NULL;
965         }
966
967         meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
968
969         if(confbase) {
970                 mesh->confbase = xstrdup(confbase);
971         }
972
973         mesh->appname = xstrdup(appname);
974         mesh->devclass = devclass;
975         mesh->discovery = true;
976         mesh->invitation_timeout = 604800; // 1 week
977
978         if(usingname) {
979                 mesh->name = xstrdup(name);
980         }
981
982         // Hash the key
983         if(key) {
984                 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
985
986                 if(!prf(key, keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
987                         logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
988                         meshlink_errno = MESHLINK_EINTERNAL;
989                         return NULL;
990                 }
991         }
992
993         // initialize mutex
994         pthread_mutexattr_t attr;
995         pthread_mutexattr_init(&attr);
996         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
997         pthread_mutex_init(&(mesh->mesh_mutex), &attr);
998
999         mesh->threadstarted = false;
1000         event_loop_init(&mesh->loop);
1001         mesh->loop.data = mesh;
1002
1003         meshlink_queue_init(&mesh->outpacketqueue);
1004
1005         // If no configuration exists yet, create it.
1006
1007         if(!main_config_exists(mesh)) {
1008                 if(!meshlink_setup(mesh)) {
1009                         logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1010                         meshlink_close(mesh);
1011                         return NULL;
1012                 }
1013         } else {
1014                 if(!meshlink_read_config(mesh)) {
1015                         logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1016                         meshlink_close(mesh);
1017                         return NULL;
1018                 }
1019         }
1020
1021 #ifdef HAVE_MINGW
1022         struct WSAData wsa_state;
1023         WSAStartup(MAKEWORD(2, 2), &wsa_state);
1024 #endif
1025
1026         // Setup up everything
1027         // TODO: we should not open listening sockets yet
1028
1029         if(!setup_network(mesh)) {
1030                 meshlink_close(mesh);
1031                 meshlink_errno = MESHLINK_ENETWORK;
1032                 return NULL;
1033         }
1034
1035         add_local_addresses(mesh);
1036         node_write_config(mesh, mesh->self);
1037
1038         idle_set(&mesh->loop, idle, mesh);
1039
1040         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1041         return mesh;
1042 }
1043
1044 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1045         if(!confbase || !*confbase) {
1046                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1047                 meshlink_errno = MESHLINK_EINVAL;
1048                 return NULL;
1049         }
1050
1051         return meshlink_open_internal(confbase, name, appname, devclass, NULL, 0);
1052 }
1053
1054 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) {
1055         if(!confbase || !*confbase) {
1056                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1057                 meshlink_errno = MESHLINK_EINVAL;
1058                 return NULL;
1059         }
1060
1061         if(!key || !keylen) {
1062                 logger(NULL, MESHLINK_ERROR, "No key given!\n");
1063                 meshlink_errno = MESHLINK_EINVAL;
1064                 return NULL;
1065         }
1066
1067         return meshlink_open_internal(confbase, name, appname, devclass, key, keylen);
1068 }
1069
1070 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1071         if(!name || !*name) {
1072                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1073                 meshlink_errno = MESHLINK_EINVAL;
1074                 return NULL;
1075         }
1076
1077         return meshlink_open_internal(NULL, name, appname, devclass, NULL, 0);
1078 }
1079
1080
1081 static void *meshlink_main_loop(void *arg) {
1082         meshlink_handle_t *mesh = arg;
1083
1084         pthread_mutex_lock(&(mesh->mesh_mutex));
1085
1086         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1087         main_loop(mesh);
1088         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1089
1090         pthread_mutex_unlock(&(mesh->mesh_mutex));
1091         return NULL;
1092 }
1093
1094 bool meshlink_start(meshlink_handle_t *mesh) {
1095         assert(mesh->self);
1096         assert(mesh->private_key);
1097
1098         if(!mesh) {
1099                 meshlink_errno = MESHLINK_EINVAL;
1100                 return false;
1101         }
1102
1103         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1104
1105         pthread_mutex_lock(&(mesh->mesh_mutex));
1106
1107         if(mesh->threadstarted) {
1108                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1109                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1110                 return true;
1111         }
1112
1113         if(mesh->listen_socket[0].tcp.fd < 0) {
1114                 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1115                 meshlink_errno = MESHLINK_ENETWORK;
1116                 return false;
1117         }
1118
1119         mesh->thedatalen = 0;
1120
1121         // TODO: open listening sockets first
1122
1123         //Check that a valid name is set
1124         if(!mesh->name) {
1125                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1126                 meshlink_errno = MESHLINK_EINVAL;
1127                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1128                 return false;
1129         }
1130
1131         init_outgoings(mesh);
1132
1133         // Start the main thread
1134
1135         event_loop_start(&mesh->loop);
1136
1137         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1138                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1139                 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1140                 meshlink_errno = MESHLINK_EINTERNAL;
1141                 event_loop_stop(&mesh->loop);
1142                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1143                 return false;
1144         }
1145
1146         mesh->threadstarted = true;
1147
1148 #if HAVE_CATTA
1149
1150         if(mesh->discovery) {
1151                 discovery_start(mesh);
1152         }
1153
1154 #endif
1155
1156         assert(mesh->self->ecdsa);
1157         assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1158
1159
1160         pthread_mutex_unlock(&(mesh->mesh_mutex));
1161         return true;
1162 }
1163
1164 void meshlink_stop(meshlink_handle_t *mesh) {
1165         if(!mesh) {
1166                 meshlink_errno = MESHLINK_EINVAL;
1167                 return;
1168         }
1169
1170         pthread_mutex_lock(&(mesh->mesh_mutex));
1171         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1172
1173 #if HAVE_CATTA
1174
1175         // Stop discovery
1176         if(mesh->discovery) {
1177                 discovery_stop(mesh);
1178         }
1179
1180 #endif
1181
1182         // Shut down the main thread
1183         event_loop_stop(&mesh->loop);
1184
1185         // Send ourselves a UDP packet to kick the event loop
1186         for(int i = 0; i < mesh->listen_sockets; i++) {
1187                 sockaddr_t sa;
1188                 socklen_t salen = sizeof(sa.sa);
1189
1190                 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1191                         logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1192                         continue;
1193                 }
1194
1195                 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1196                         logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1197                 }
1198         }
1199
1200         if(mesh->threadstarted) {
1201                 // Wait for the main thread to finish
1202                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1203                 pthread_join(mesh->thread, NULL);
1204                 pthread_mutex_lock(&(mesh->mesh_mutex));
1205
1206                 mesh->threadstarted = false;
1207         }
1208
1209         // Close all metaconnections
1210         if(mesh->connections) {
1211                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1212                         next = node->next;
1213                         connection_t *c = node->data;
1214                         c->outgoing = NULL;
1215                         terminate_connection(mesh, c, false);
1216                 }
1217         }
1218
1219         exit_outgoings(mesh);
1220
1221         pthread_mutex_unlock(&(mesh->mesh_mutex));
1222 }
1223
1224 void meshlink_close(meshlink_handle_t *mesh) {
1225         if(!mesh || !mesh->confbase) {
1226                 meshlink_errno = MESHLINK_EINVAL;
1227                 return;
1228         }
1229
1230         // stop can be called even if mesh has not been started
1231         meshlink_stop(mesh);
1232
1233         // lock is not released after this
1234         pthread_mutex_lock(&(mesh->mesh_mutex));
1235
1236         // Close and free all resources used.
1237
1238         close_network_connections(mesh);
1239
1240         logger(mesh, MESHLINK_INFO, "Terminating");
1241
1242         event_loop_exit(&mesh->loop);
1243
1244 #ifdef HAVE_MINGW
1245
1246         if(mesh->confbase) {
1247                 WSACleanup();
1248         }
1249
1250 #endif
1251
1252         ecdsa_free(mesh->invitation_key);
1253
1254         free(mesh->name);
1255         free(mesh->appname);
1256         free(mesh->confbase);
1257         pthread_mutex_destroy(&(mesh->mesh_mutex));
1258
1259         main_config_unlock(mesh);
1260
1261         memset(mesh, 0, sizeof(*mesh));
1262
1263         free(mesh);
1264 }
1265
1266 bool meshlink_destroy(const char *confbase) {
1267         if(!confbase) {
1268                 meshlink_errno = MESHLINK_EINVAL;
1269                 return false;
1270         }
1271
1272         return config_destroy(confbase);
1273 }
1274
1275 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1276         if(!mesh) {
1277                 meshlink_errno = MESHLINK_EINVAL;
1278                 return;
1279         }
1280
1281         pthread_mutex_lock(&(mesh->mesh_mutex));
1282         mesh->receive_cb = cb;
1283         pthread_mutex_unlock(&(mesh->mesh_mutex));
1284 }
1285
1286 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1287         if(!mesh) {
1288                 meshlink_errno = MESHLINK_EINVAL;
1289                 return;
1290         }
1291
1292         pthread_mutex_lock(&(mesh->mesh_mutex));
1293         mesh->node_status_cb = cb;
1294         pthread_mutex_unlock(&(mesh->mesh_mutex));
1295 }
1296
1297 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1298         if(!mesh) {
1299                 meshlink_errno = MESHLINK_EINVAL;
1300                 return;
1301         }
1302
1303         pthread_mutex_lock(&(mesh->mesh_mutex));
1304         mesh->node_duplicate_cb = cb;
1305         pthread_mutex_unlock(&(mesh->mesh_mutex));
1306 }
1307
1308 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1309         if(mesh) {
1310                 pthread_mutex_lock(&(mesh->mesh_mutex));
1311                 mesh->log_cb = cb;
1312                 mesh->log_level = cb ? level : 0;
1313                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1314         } else {
1315                 global_log_cb = cb;
1316                 global_log_level = cb ? level : 0;
1317         }
1318 }
1319
1320 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1321         meshlink_packethdr_t *hdr;
1322
1323         // Validate arguments
1324         if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1325                 meshlink_errno = MESHLINK_EINVAL;
1326                 return false;
1327         }
1328
1329         if(!len) {
1330                 return true;
1331         }
1332
1333         if(!data) {
1334                 meshlink_errno = MESHLINK_EINVAL;
1335                 return false;
1336         }
1337
1338         // Prepare the packet
1339         vpn_packet_t *packet = malloc(sizeof(*packet));
1340
1341         if(!packet) {
1342                 meshlink_errno = MESHLINK_ENOMEM;
1343                 return false;
1344         }
1345
1346         packet->probe = false;
1347         packet->tcp = false;
1348         packet->len = len + sizeof(*hdr);
1349
1350         hdr = (meshlink_packethdr_t *)packet->data;
1351         memset(hdr, 0, sizeof(*hdr));
1352         // leave the last byte as 0 to make sure strings are always
1353         // null-terminated if they are longer than the buffer
1354         strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1355         strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1356
1357         memcpy(packet->data + sizeof(*hdr), data, len);
1358
1359         // Queue it
1360         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1361                 free(packet);
1362                 meshlink_errno = MESHLINK_ENOMEM;
1363                 return false;
1364         }
1365
1366         // Notify event loop
1367         signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1368
1369         return true;
1370 }
1371
1372 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1373         (void)loop;
1374         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1375
1376         if(!packet) {
1377                 return;
1378         }
1379
1380         mesh->self->in_packets++;
1381         mesh->self->in_bytes += packet->len;
1382         route(mesh, mesh->self, packet);
1383 }
1384
1385 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1386         if(!mesh || !destination) {
1387                 meshlink_errno = MESHLINK_EINVAL;
1388                 return -1;
1389         }
1390
1391         pthread_mutex_lock(&(mesh->mesh_mutex));
1392
1393         node_t *n = (node_t *)destination;
1394
1395         if(!n->status.reachable) {
1396                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1397                 return 0;
1398
1399         } else if(n->mtuprobes > 30 && n->minmtu) {
1400                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1401                 return n->minmtu;
1402         } else {
1403                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1404                 return MTU;
1405         }
1406 }
1407
1408 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1409         if(!mesh || !node) {
1410                 meshlink_errno = MESHLINK_EINVAL;
1411                 return NULL;
1412         }
1413
1414         pthread_mutex_lock(&(mesh->mesh_mutex));
1415
1416         node_t *n = (node_t *)node;
1417
1418         if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1419                 meshlink_errno = MESHLINK_EINTERNAL;
1420                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1421                 return false;
1422         }
1423
1424         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1425
1426         if(!fingerprint) {
1427                 meshlink_errno = MESHLINK_EINTERNAL;
1428         }
1429
1430         pthread_mutex_unlock(&(mesh->mesh_mutex));
1431         return fingerprint;
1432 }
1433
1434 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1435         if(!mesh) {
1436                 meshlink_errno = MESHLINK_EINVAL;
1437                 return NULL;
1438         }
1439
1440         return (meshlink_node_t *)mesh->self;
1441 }
1442
1443 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1444         if(!mesh || !name) {
1445                 meshlink_errno = MESHLINK_EINVAL;
1446                 return NULL;
1447         }
1448
1449         meshlink_node_t *node = NULL;
1450
1451         pthread_mutex_lock(&(mesh->mesh_mutex));
1452         node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1453         pthread_mutex_unlock(&(mesh->mesh_mutex));
1454         return node;
1455 }
1456
1457 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1458         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1459                 meshlink_errno = MESHLINK_EINVAL;
1460                 return NULL;
1461         }
1462
1463         meshlink_node_t **result;
1464
1465         //lock mesh->nodes
1466         pthread_mutex_lock(&(mesh->mesh_mutex));
1467
1468         *nmemb = mesh->nodes->count;
1469         result = realloc(nodes, *nmemb * sizeof(*nodes));
1470
1471         if(result) {
1472                 meshlink_node_t **p = result;
1473
1474                 for splay_each(node_t, n, mesh->nodes) {
1475                         *p++ = (meshlink_node_t *)n;
1476                 }
1477         } else {
1478                 *nmemb = 0;
1479                 free(nodes);
1480                 meshlink_errno = MESHLINK_ENOMEM;
1481         }
1482
1483         pthread_mutex_unlock(&(mesh->mesh_mutex));
1484
1485         return result;
1486 }
1487
1488 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1489         if(!mesh || !data || !len || !signature || !siglen) {
1490                 meshlink_errno = MESHLINK_EINVAL;
1491                 return false;
1492         }
1493
1494         if(*siglen < MESHLINK_SIGLEN) {
1495                 meshlink_errno = MESHLINK_EINVAL;
1496                 return false;
1497         }
1498
1499         pthread_mutex_lock(&(mesh->mesh_mutex));
1500
1501         if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1502                 meshlink_errno = MESHLINK_EINTERNAL;
1503                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1504                 return false;
1505         }
1506
1507         *siglen = MESHLINK_SIGLEN;
1508         pthread_mutex_unlock(&(mesh->mesh_mutex));
1509         return true;
1510 }
1511
1512 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1513         if(!mesh || !data || !len || !signature) {
1514                 meshlink_errno = MESHLINK_EINVAL;
1515                 return false;
1516         }
1517
1518         if(siglen != MESHLINK_SIGLEN) {
1519                 meshlink_errno = MESHLINK_EINVAL;
1520                 return false;
1521         }
1522
1523         pthread_mutex_lock(&(mesh->mesh_mutex));
1524
1525         bool rval = false;
1526
1527         struct node_t *n = (struct node_t *)source;
1528
1529         if(!node_read_public_key(mesh, n)) {
1530                 meshlink_errno = MESHLINK_EINTERNAL;
1531                 rval = false;
1532         } else {
1533                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1534         }
1535
1536         pthread_mutex_unlock(&(mesh->mesh_mutex));
1537         return rval;
1538 }
1539
1540 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1541         pthread_mutex_lock(&(mesh->mesh_mutex));
1542
1543         size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
1544
1545         if(!count) {
1546                 // TODO: Update invitation key if necessary?
1547         }
1548
1549         pthread_mutex_unlock(&(mesh->mesh_mutex));
1550
1551         return mesh->invitation_key;
1552 }
1553
1554 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1555         if(!mesh || !node || !address) {
1556                 meshlink_errno = MESHLINK_EINVAL;
1557                 return false;
1558         }
1559
1560         if(!is_valid_hostname(address)) {
1561                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1562                 meshlink_errno = MESHLINK_EINVAL;
1563                 return false;
1564         }
1565
1566         if(port && !is_valid_port(port)) {
1567                 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1568                 meshlink_errno = MESHLINK_EINVAL;
1569                 return false;
1570         }
1571
1572         char *canonical_address;
1573
1574         if(port) {
1575                 xasprintf(&canonical_address, "%s %s", address, port);
1576         } else {
1577                 canonical_address = xstrdup(address);
1578         }
1579
1580         pthread_mutex_lock(&(mesh->mesh_mutex));
1581
1582         node_t *n = (node_t *)node;
1583         free(n->canonical_address);
1584         n->canonical_address = canonical_address;
1585         n->status.dirty = true;
1586
1587         pthread_mutex_unlock(&(mesh->mesh_mutex));
1588
1589         return true;
1590 }
1591
1592 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1593         return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1594 }
1595
1596 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1597         if(!mesh) {
1598                 meshlink_errno = MESHLINK_EINVAL;
1599                 return false;
1600         }
1601
1602         char *address = meshlink_get_external_address(mesh);
1603
1604         if(!address) {
1605                 return false;
1606         }
1607
1608         bool rval = meshlink_add_address(mesh, address);
1609         free(address);
1610
1611         return rval;
1612 }
1613
1614 int meshlink_get_port(meshlink_handle_t *mesh) {
1615         if(!mesh) {
1616                 meshlink_errno = MESHLINK_EINVAL;
1617                 return -1;
1618         }
1619
1620         if(!mesh->myport) {
1621                 meshlink_errno = MESHLINK_EINTERNAL;
1622                 return -1;
1623         }
1624
1625         return atoi(mesh->myport);
1626 }
1627
1628 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1629         if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1630                 meshlink_errno = MESHLINK_EINVAL;
1631                 return false;
1632         }
1633
1634         if(mesh->myport && port == atoi(mesh->myport)) {
1635                 return true;
1636         }
1637
1638         if(!try_bind(port)) {
1639                 meshlink_errno = MESHLINK_ENETWORK;
1640                 return false;
1641         }
1642
1643         bool rval = false;
1644
1645         pthread_mutex_lock(&(mesh->mesh_mutex));
1646
1647         if(mesh->threadstarted) {
1648                 meshlink_errno = MESHLINK_EINVAL;
1649                 goto done;
1650         }
1651
1652         close_network_connections(mesh);
1653
1654         // TODO: write meshlink.conf again
1655
1656         if(!setup_network(mesh)) {
1657                 meshlink_errno = MESHLINK_ENETWORK;
1658         } else {
1659                 rval = true;
1660         }
1661
1662 done:
1663         pthread_mutex_unlock(&(mesh->mesh_mutex));
1664
1665         return rval;
1666 }
1667
1668 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
1669         mesh->invitation_timeout = timeout;
1670 }
1671
1672 char *meshlink_invite_ex(meshlink_handle_t *mesh, const char *name, uint32_t flags) {
1673         if(!mesh) {
1674                 meshlink_errno = MESHLINK_EINVAL;
1675                 return NULL;
1676         }
1677
1678         pthread_mutex_lock(&(mesh->mesh_mutex));
1679
1680         // Check validity of the new node's name
1681         if(!check_id(name)) {
1682                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1683                 meshlink_errno = MESHLINK_EINVAL;
1684                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1685                 return NULL;
1686         }
1687
1688         // Ensure no host configuration file with that name exists
1689         if(config_exists(mesh, name)) {
1690                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1691                 meshlink_errno = MESHLINK_EEXIST;
1692                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1693                 return NULL;
1694         }
1695
1696         // Ensure no other nodes know about this name
1697         if(meshlink_get_node(mesh, name)) {
1698                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1699                 meshlink_errno = MESHLINK_EEXIST;
1700                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1701                 return NULL;
1702         }
1703
1704         // Get the local address
1705         char *address = get_my_hostname(mesh, flags);
1706
1707         if(!address) {
1708                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1709                 meshlink_errno = MESHLINK_ERESOLV;
1710                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1711                 return NULL;
1712         }
1713
1714         if(!refresh_invitation_key(mesh)) {
1715                 meshlink_errno = MESHLINK_EINTERNAL;
1716                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1717                 return NULL;
1718         }
1719
1720         char hash[64];
1721
1722         // Create a hash of the key.
1723         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1724         sha512(fingerprint, strlen(fingerprint), hash);
1725         b64encode_urlsafe(hash, hash, 18);
1726
1727         // Create a random cookie for this invitation.
1728         char cookie[25];
1729         randomize(cookie, 18);
1730
1731         // Create a filename that doesn't reveal the cookie itself
1732         char buf[18 + strlen(fingerprint)];
1733         char cookiehash[64];
1734         memcpy(buf, cookie, 18);
1735         memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1736         sha512(buf, sizeof(buf), cookiehash);
1737         b64encode_urlsafe(cookiehash, cookiehash, 18);
1738
1739         b64encode_urlsafe(cookie, cookie, 18);
1740
1741         free(fingerprint);
1742
1743         /* Construct the invitation file */
1744         uint8_t outbuf[4096];
1745         packmsg_output_t inv = {outbuf, sizeof(outbuf)};
1746
1747         packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
1748         packmsg_add_str(&inv, name);
1749         packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
1750
1751         /* TODO: Add several host config files to bootstrap connections */
1752         config_t configs[5] = {NULL};
1753         int count = 0;
1754
1755         if(config_read(mesh, mesh->self->name, &configs[count])) {
1756                 count++;
1757         }
1758
1759         /* Append host config files to the invitation file */
1760         packmsg_add_array(&inv, count);
1761
1762         for(int i = 0; i < count; i++) {
1763                 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
1764                 config_free(&configs[i]);
1765         }
1766
1767         config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
1768
1769         if(!invitation_write(mesh, cookiehash, &config)) {
1770                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
1771                 meshlink_errno = MESHLINK_ESTORAGE;
1772                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1773                 return NULL;
1774         }
1775
1776         // Create an URL from the local address, key hash and cookie
1777         char *url;
1778         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1779         free(address);
1780
1781         pthread_mutex_unlock(&(mesh->mesh_mutex));
1782         return url;
1783 }
1784
1785 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1786         return meshlink_invite_ex(mesh, name, 0);
1787 }
1788
1789 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1790         if(!mesh || !invitation) {
1791                 meshlink_errno = MESHLINK_EINVAL;
1792                 return false;
1793         }
1794
1795         pthread_mutex_lock(&(mesh->mesh_mutex));
1796
1797         //Before doing meshlink_join make sure we are not connected to another mesh
1798         if(mesh->threadstarted) {
1799                 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
1800                 meshlink_errno = MESHLINK_EINVAL;
1801                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1802                 return false;
1803         }
1804
1805         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1806         char copy[strlen(invitation) + 1];
1807         strcpy(copy, invitation);
1808
1809         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
1810
1811         char *slash = strchr(copy, '/');
1812
1813         if(!slash) {
1814                 goto invalid;
1815         }
1816
1817         *slash++ = 0;
1818
1819         if(strlen(slash) != 48) {
1820                 goto invalid;
1821         }
1822
1823         char *address = copy;
1824         char *port = NULL;
1825
1826         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
1827                 goto invalid;
1828         }
1829
1830         // Generate a throw-away key for the invitation.
1831         ecdsa_t *key = ecdsa_generate();
1832
1833         if(!key) {
1834                 meshlink_errno = MESHLINK_EINTERNAL;
1835                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1836                 return false;
1837         }
1838
1839         char *b64key = ecdsa_get_base64_public_key(key);
1840         char *comma;
1841         mesh->sock = -1;
1842
1843         while(address && *address) {
1844                 // We allow commas in the address part to support multiple addresses in one invitation URL.
1845                 comma = strchr(address, ',');
1846
1847                 if(comma) {
1848                         *comma++ = 0;
1849                 }
1850
1851                 // Split of the port
1852                 port = strrchr(address, ':');
1853
1854                 if(!port) {
1855                         goto invalid;
1856                 }
1857
1858                 *port++ = 0;
1859
1860                 // IPv6 address are enclosed in brackets, per RFC 3986
1861                 if(*address == '[') {
1862                         address++;
1863                         char *bracket = strchr(address, ']');
1864
1865                         if(!bracket) {
1866                                 goto invalid;
1867                         }
1868
1869                         *bracket++ = 0;
1870
1871                         if(*bracket) {
1872                                 goto invalid;
1873                         }
1874                 }
1875
1876                 // Connect to the meshlink daemon mentioned in the URL.
1877                 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1878
1879                 if(ai) {
1880                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
1881                                 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
1882
1883                                 if(mesh->sock == -1) {
1884                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1885                                         meshlink_errno = MESHLINK_ENETWORK;
1886                                         continue;
1887                                 }
1888
1889                                 set_timeout(mesh->sock, 5000);
1890
1891                                 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
1892                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1893                                         meshlink_errno = MESHLINK_ENETWORK;
1894                                         closesocket(mesh->sock);
1895                                         mesh->sock = -1;
1896                                         continue;
1897                                 }
1898                         }
1899
1900                         freeaddrinfo(ai);
1901                 } else {
1902                         meshlink_errno = MESHLINK_ERESOLV;
1903                 }
1904
1905                 if(mesh->sock != -1 || !comma) {
1906                         break;
1907                 }
1908
1909                 address = comma;
1910         }
1911
1912         if(mesh->sock == -1) {
1913                 pthread_mutex_unlock(&mesh->mesh_mutex);
1914                 return false;
1915         }
1916
1917         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1918
1919         // Tell him we have an invitation, and give him our throw-away key.
1920
1921         mesh->blen = 0;
1922
1923         if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
1924                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1925                 closesocket(mesh->sock);
1926                 meshlink_errno = MESHLINK_ENETWORK;
1927                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1928                 return false;
1929         }
1930
1931         free(b64key);
1932
1933         char hisname[4096] = "";
1934         int code, hismajor, hisminor = 0;
1935
1936         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) {
1937                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1938                 closesocket(mesh->sock);
1939                 meshlink_errno = MESHLINK_ENETWORK;
1940                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1941                 return false;
1942         }
1943
1944         // Check if the hash of the key he gave us matches the hash in the URL.
1945         char *fingerprint = mesh->line + 2;
1946         char hishash[64];
1947
1948         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1949                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1950                 meshlink_errno = MESHLINK_EINTERNAL;
1951                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1952                 return false;
1953         }
1954
1955         if(memcmp(hishash, mesh->hash, 18)) {
1956                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1957                 meshlink_errno = MESHLINK_EPEER;
1958                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1959                 return false;
1960
1961         }
1962
1963         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1964
1965         if(!hiskey) {
1966                 meshlink_errno = MESHLINK_EINTERNAL;
1967                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1968                 return false;
1969         }
1970
1971         // Start an SPTPS session
1972         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
1973                 meshlink_errno = MESHLINK_EINTERNAL;
1974                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1975                 return false;
1976         }
1977
1978         // Feed rest of input buffer to SPTPS
1979         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1980                 meshlink_errno = MESHLINK_EPEER;
1981                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1982                 return false;
1983         }
1984
1985         int len;
1986
1987         while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
1988                 if(len < 0) {
1989                         if(errno == EINTR) {
1990                                 continue;
1991                         }
1992
1993                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1994                         meshlink_errno = MESHLINK_ENETWORK;
1995                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1996                         return false;
1997                 }
1998
1999                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2000                         meshlink_errno = MESHLINK_EPEER;
2001                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2002                         return false;
2003                 }
2004         }
2005
2006         sptps_stop(&mesh->sptps);
2007         ecdsa_free(hiskey);
2008         ecdsa_free(key);
2009         closesocket(mesh->sock);
2010
2011         if(!mesh->success) {
2012                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2013                 meshlink_errno = MESHLINK_EPEER;
2014                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2015                 return false;
2016         }
2017
2018         pthread_mutex_unlock(&(mesh->mesh_mutex));
2019         return true;
2020
2021 invalid:
2022         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2023         meshlink_errno = MESHLINK_EINVAL;
2024         pthread_mutex_unlock(&(mesh->mesh_mutex));
2025         return false;
2026 }
2027
2028 char *meshlink_export(meshlink_handle_t *mesh) {
2029         if(!mesh) {
2030                 meshlink_errno = MESHLINK_EINVAL;
2031                 return NULL;
2032         }
2033
2034         // Create a config file on the fly.
2035
2036         uint8_t buf[4096];
2037         packmsg_output_t out = {buf, sizeof(buf)};
2038         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2039         packmsg_add_str(&out, mesh->name);
2040
2041         pthread_mutex_lock(&(mesh->mesh_mutex));
2042
2043         packmsg_add_int32(&out, mesh->self->devclass);
2044         packmsg_add_bool(&out, mesh->self->status.blacklisted);
2045         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2046         packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2047
2048         uint32_t count = 0;
2049
2050         for(uint32_t i = 0; i < 5; i++) {
2051                 if(mesh->self->recent[i].sa.sa_family) {
2052                         count++;
2053                 } else {
2054                         break;
2055                 }
2056         }
2057
2058         packmsg_add_array(&out, count);
2059
2060         for(uint32_t i = 0; i < count; i++) {
2061                 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2062         }
2063
2064         pthread_mutex_unlock(&(mesh->mesh_mutex));
2065
2066         if(!packmsg_output_ok(&out)) {
2067                 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2068                 meshlink_errno = MESHLINK_EINTERNAL;
2069                 return NULL;
2070         }
2071
2072         // Prepare a base64-encoded packmsg array containing our config file
2073
2074         uint32_t len = packmsg_output_size(&out, buf);
2075         uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2076         uint8_t *buf2 = xmalloc(len2);
2077         packmsg_output_t out2 = {buf2, len2};
2078         packmsg_add_array(&out2, 1);
2079         packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2080
2081         if(!packmsg_output_ok(&out2)) {
2082                 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2083                 meshlink_errno = MESHLINK_EINTERNAL;
2084                 free(buf2);
2085                 return NULL;
2086         }
2087
2088         b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2089
2090         return (char *)buf2;
2091 }
2092
2093 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2094         if(!mesh || !data) {
2095                 abort();
2096                 meshlink_errno = MESHLINK_EINVAL;
2097                 return false;
2098         }
2099
2100         size_t datalen = strlen(data);
2101         uint8_t *buf = xmalloc(datalen);
2102         int buflen = b64decode(data, buf, datalen);
2103
2104         if(!buflen) {
2105                 abort();
2106                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2107                 meshlink_errno = MESHLINK_EPEER;
2108                 return false;
2109         }
2110
2111         packmsg_input_t in = {buf, buflen};
2112         uint32_t count = packmsg_get_array(&in);
2113
2114         if(!count) {
2115                 abort();
2116                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2117                 meshlink_errno = MESHLINK_EPEER;
2118                 return false;
2119         }
2120
2121         pthread_mutex_lock(&(mesh->mesh_mutex));
2122
2123         while(count--) {
2124                 const void *data;
2125                 uint32_t len = packmsg_get_bin_raw(&in, &data);
2126
2127                 if(!len) {
2128                         break;
2129                 }
2130
2131                 packmsg_input_t in2 = {data, len};
2132                 uint32_t version = packmsg_get_uint32(&in2);
2133                 char *name = packmsg_get_str_dup(&in2);
2134
2135                 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2136                         free(name);
2137                         packmsg_input_invalidate(&in2);
2138                         break;
2139                 }
2140
2141                 if(!check_id(name)) {
2142                         free(name);
2143                         break;
2144                 }
2145
2146                 node_t *n = lookup_node(mesh, name);
2147
2148                 if(n) {
2149                         free(name);
2150                         logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2151                         continue;
2152                 }
2153
2154                 n = new_node();
2155                 n->name = name;
2156                 n->devclass = packmsg_get_int32(&in2);
2157                 n->status.blacklisted = packmsg_get_bool(&in2);
2158                 const void *key;
2159                 uint32_t keylen = packmsg_get_bin_raw(&in2, &key);
2160
2161                 if(keylen == 32) {
2162                         n->ecdsa = ecdsa_set_public_key(key);
2163                 }
2164
2165                 n->canonical_address = packmsg_get_str_dup(&in2);
2166                 uint32_t count = packmsg_get_array(&in2);
2167
2168                 if(count > 5) {
2169                         count = 5;
2170                 }
2171
2172                 for(uint32_t i = 0; i < count; i++) {
2173                         n->recent[i] = packmsg_get_sockaddr(&in2);
2174                 }
2175
2176                 if(!packmsg_done(&in2) || keylen != 32) {
2177                         abort();
2178                         packmsg_input_invalidate(&in2);
2179                         free_node(n);
2180                 } else {
2181                         config_t config = {data, len};
2182                         config_write(mesh, n->name, &config);
2183                         node_add(mesh, n);
2184                 }
2185         }
2186
2187         pthread_mutex_unlock(&(mesh->mesh_mutex));
2188
2189         if(!packmsg_done(&in)) {
2190                 abort();
2191                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2192                 meshlink_errno = MESHLINK_EPEER;
2193                 return false;
2194         }
2195
2196         return true;
2197 }
2198
2199 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2200         if(!mesh || !node) {
2201                 meshlink_errno = MESHLINK_EINVAL;
2202                 return;
2203         }
2204
2205         pthread_mutex_lock(&(mesh->mesh_mutex));
2206
2207         node_t *n;
2208         n = (node_t *)node;
2209         n->status.blacklisted = true;
2210         n->status.dirty = true;
2211         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2212
2213         //Immediately terminate any connections we have with the blacklisted node
2214         for list_each(connection_t, c, mesh->connections) {
2215                 if(c->node == n) {
2216                         terminate_connection(mesh, c, c->status.active);
2217                 }
2218         }
2219
2220         pthread_mutex_unlock(&(mesh->mesh_mutex));
2221 }
2222
2223 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2224         if(!mesh || !node) {
2225                 meshlink_errno = MESHLINK_EINVAL;
2226                 return;
2227         }
2228
2229         pthread_mutex_lock(&(mesh->mesh_mutex));
2230
2231         node_t *n = (node_t *)node;
2232         n->status.blacklisted = false;
2233         n->status.dirty = true;
2234
2235         pthread_mutex_unlock(&(mesh->mesh_mutex));
2236         return;
2237 }
2238
2239 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2240         mesh->default_blacklist = blacklist;
2241 }
2242
2243 /* Hint that a hostname may be found at an address
2244  * See header file for detailed comment.
2245  */
2246 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2247         if(!mesh || !node || !addr) {
2248                 meshlink_errno = EINVAL;
2249                 return;
2250         }
2251
2252         pthread_mutex_lock(&(mesh->mesh_mutex));
2253
2254         node_t *n = (node_t *)node;
2255         memmove(n->recent + 1, n->recent, 4 * sizeof(*n->recent));
2256         memcpy(n->recent, addr, SALEN(*addr));
2257         n->status.dirty = true;
2258
2259         pthread_mutex_unlock(&(mesh->mesh_mutex));
2260         // @TODO do we want to fire off a connection attempt right away?
2261 }
2262
2263 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2264         (void)port;
2265         node_t *n = utcp->priv;
2266         meshlink_handle_t *mesh = n->mesh;
2267         return mesh->channel_accept_cb;
2268 }
2269
2270 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2271         meshlink_channel_t *channel = connection->priv;
2272
2273         if(!channel) {
2274                 abort();
2275         }
2276
2277         node_t *n = channel->node;
2278         meshlink_handle_t *mesh = n->mesh;
2279
2280         if(n->status.destroyed) {
2281                 meshlink_channel_close(mesh, channel);
2282         } else if(channel->receive_cb) {
2283                 channel->receive_cb(mesh, channel, data, len);
2284         }
2285
2286         return len;
2287 }
2288
2289 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2290         node_t *n = utcp_connection->utcp->priv;
2291
2292         if(!n) {
2293                 abort();
2294         }
2295
2296         meshlink_handle_t *mesh = n->mesh;
2297
2298         if(!mesh->channel_accept_cb) {
2299                 return;
2300         }
2301
2302         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2303         channel->node = n;
2304         channel->c = utcp_connection;
2305
2306         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2307                 utcp_accept(utcp_connection, channel_recv, channel);
2308         } else {
2309                 free(channel);
2310         }
2311 }
2312
2313 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2314         node_t *n = utcp->priv;
2315
2316         if(n->status.destroyed) {
2317                 return -1;
2318         }
2319
2320         meshlink_handle_t *mesh = n->mesh;
2321         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2322 }
2323
2324 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2325         if(!mesh || !channel) {
2326                 meshlink_errno = MESHLINK_EINVAL;
2327                 return;
2328         }
2329
2330         channel->receive_cb = cb;
2331 }
2332
2333 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2334         (void)mesh;
2335         node_t *n = (node_t *)source;
2336
2337         if(!n->utcp) {
2338                 abort();
2339         }
2340
2341         utcp_recv(n->utcp, data, len);
2342 }
2343
2344 static void channel_poll(struct utcp_connection *connection, size_t len) {
2345         meshlink_channel_t *channel = connection->priv;
2346
2347         if(!channel) {
2348                 abort();
2349         }
2350
2351         node_t *n = channel->node;
2352         meshlink_handle_t *mesh = n->mesh;
2353
2354         if(channel->poll_cb) {
2355                 channel->poll_cb(mesh, channel, len);
2356         }
2357 }
2358
2359 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2360         (void)mesh;
2361         channel->poll_cb = cb;
2362         utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2363 }
2364
2365 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2366         if(!mesh) {
2367                 meshlink_errno = MESHLINK_EINVAL;
2368                 return;
2369         }
2370
2371         pthread_mutex_lock(&mesh->mesh_mutex);
2372         mesh->channel_accept_cb = cb;
2373         mesh->receive_cb = channel_receive;
2374
2375         for splay_each(node_t, n, mesh->nodes) {
2376                 if(!n->utcp && n != mesh->self) {
2377                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2378                 }
2379         }
2380
2381         pthread_mutex_unlock(&mesh->mesh_mutex);
2382 }
2383
2384 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) {
2385         if(data || len) {
2386                 abort();        // TODO: handle non-NULL data
2387         }
2388
2389         if(!mesh || !node) {
2390                 meshlink_errno = MESHLINK_EINVAL;
2391                 return NULL;
2392         }
2393
2394         node_t *n = (node_t *)node;
2395
2396         if(!n->utcp) {
2397                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2398                 mesh->receive_cb = channel_receive;
2399
2400                 if(!n->utcp) {
2401                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2402                         return NULL;
2403                 }
2404         }
2405
2406         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2407         channel->node = n;
2408         channel->receive_cb = cb;
2409         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2410
2411         if(!channel->c) {
2412                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2413                 free(channel);
2414                 return NULL;
2415         }
2416
2417         return channel;
2418 }
2419
2420 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) {
2421         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2422 }
2423
2424 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2425         if(!mesh || !channel) {
2426                 meshlink_errno = MESHLINK_EINVAL;
2427                 return;
2428         }
2429
2430         utcp_shutdown(channel->c, direction);
2431 }
2432
2433 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2434         if(!mesh || !channel) {
2435                 meshlink_errno = MESHLINK_EINVAL;
2436                 return;
2437         }
2438
2439         utcp_close(channel->c);
2440         free(channel);
2441 }
2442
2443 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2444         if(!mesh || !channel) {
2445                 meshlink_errno = MESHLINK_EINVAL;
2446                 return -1;
2447         }
2448
2449         if(!len) {
2450                 return 0;
2451         }
2452
2453         if(!data) {
2454                 meshlink_errno = MESHLINK_EINVAL;
2455                 return -1;
2456         }
2457
2458         // TODO: more finegrained locking.
2459         // Ideally we want to put the data into the UTCP connection's send buffer.
2460         // Then, preferrably only if there is room in the receiver window,
2461         // kick the meshlink thread to go send packets.
2462
2463         pthread_mutex_lock(&mesh->mesh_mutex);
2464         ssize_t retval = utcp_send(channel->c, data, len);
2465         pthread_mutex_unlock(&mesh->mesh_mutex);
2466
2467         if(retval < 0) {
2468                 meshlink_errno = MESHLINK_ENETWORK;
2469         }
2470
2471         return retval;
2472 }
2473
2474 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2475         if(!mesh || !channel) {
2476                 meshlink_errno = MESHLINK_EINVAL;
2477                 return -1;
2478         }
2479
2480         return channel->c->flags;
2481 }
2482
2483 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2484         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2485                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2486         }
2487
2488         if(mesh->node_status_cb) {
2489                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2490         }
2491 }
2492
2493 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2494         if(!mesh->node_duplicate_cb || n->status.duplicate) {
2495                 return;
2496         }
2497
2498         n->status.duplicate = true;
2499         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2500 }
2501
2502 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2503 #if HAVE_CATTA
2504
2505         if(!mesh) {
2506                 meshlink_errno = MESHLINK_EINVAL;
2507                 return;
2508         }
2509
2510         pthread_mutex_lock(&mesh->mesh_mutex);
2511
2512         if(mesh->discovery == enable) {
2513                 goto end;
2514         }
2515
2516         if(mesh->threadstarted) {
2517                 if(enable) {
2518                         discovery_start(mesh);
2519                 } else {
2520                         discovery_stop(mesh);
2521                 }
2522         }
2523
2524         mesh->discovery = enable;
2525
2526 end:
2527         pthread_mutex_unlock(&mesh->mesh_mutex);
2528 #else
2529         (void)mesh;
2530         (void)enable;
2531         meshlink_errno = MESHLINK_ENOTSUP;
2532 #endif
2533 }
2534
2535 static void __attribute__((constructor)) meshlink_init(void) {
2536         crypto_init();
2537         unsigned int seed;
2538         randomize(&seed, sizeof(seed));
2539         srand(seed);
2540 }
2541
2542 static void __attribute__((destructor)) meshlink_exit(void) {
2543         crypto_exit();
2544 }
2545
2546 /// Device class traits
2547 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2548         { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2549         { .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
2550         { .min_connects = 3, .max_connects = 3, .edge_weight = 6 },             // DEV_CLASS_PORTABLE
2551         { .min_connects = 1, .max_connects = 1, .edge_weight = 9 },             // DEV_CLASS_UNKNOWN
2552 };