]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Fall back to getifaddrs() to get an interface address if there is no default route.
[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 "submesh.h"
30 #include "packmsg.h"
31 #include "prf.h"
32 #include "protocol.h"
33 #include "route.h"
34 #include "sockaddr.h"
35 #include "utils.h"
36 #include "xalloc.h"
37 #include "ed25519/sha512.h"
38 #include "discovery.h"
39 #include "devtools.h"
40 #include "graph.h"
41
42 #ifndef MSG_NOSIGNAL
43 #define MSG_NOSIGNAL 0
44 #endif
45 __thread meshlink_errno_t meshlink_errno;
46 meshlink_log_cb_t global_log_cb;
47 meshlink_log_level_t global_log_level;
48
49 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
50
51 static int rstrip(char *value) {
52         int len = strlen(value);
53
54         while(len && strchr("\t\r\n ", value[len - 1])) {
55                 value[--len] = 0;
56         }
57
58         return len;
59 }
60
61 static void get_canonical_address(node_t *n, char **hostname, char **port) {
62         if(!n->canonical_address) {
63                 return;
64         }
65
66         *hostname = xstrdup(n->canonical_address);
67         char *space = strchr(*hostname, ' ');
68
69         if(space) {
70                 *space++ = 0;
71                 *port = xstrdup(space);
72         }
73 }
74
75 static bool is_valid_hostname(const char *hostname) {
76         if(!*hostname) {
77                 return false;
78         }
79
80         for(const char *p = hostname; *p; p++) {
81                 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
82                         return false;
83                 }
84         }
85
86         return true;
87 }
88
89 static bool is_valid_port(const char *port) {
90         if(!*port) {
91                 return false;
92         }
93
94         if(isdigit(*port)) {
95                 char *end;
96                 unsigned long int result = strtoul(port, &end, 10);
97                 return result && result < 65536 && !*end;
98         }
99
100         for(const char *p = port; *p; p++) {
101                 if(!(isalnum(*p) || *p == '-')) {
102                         return false;
103                 }
104         }
105
106         return true;
107 }
108
109 static void set_timeout(int sock, int timeout) {
110 #ifdef _WIN32
111         DWORD tv = timeout;
112 #else
113         struct timeval tv;
114         tv.tv_sec = timeout / 1000;
115         tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
116 #endif
117         setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
118         setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
119 }
120
121 struct socket_in_netns_params {
122         int domain;
123         int type;
124         int protocol;
125         int netns;
126         int fd;
127 };
128
129 #ifdef HAVE_SETNS
130 static void *socket_in_netns_thread(void *arg) {
131         struct socket_in_netns_params *params = arg;
132
133         if(setns(params->netns, CLONE_NEWNET) == -1) {
134                 meshlink_errno = MESHLINK_EINVAL;
135                 return NULL;
136         }
137
138         params->fd = socket(params->domain, params->type, params->protocol);
139
140         return NULL;
141 }
142 #endif // HAVE_SETNS
143
144 static int socket_in_netns(int domain, int type, int protocol, int netns) {
145         if(netns == -1) {
146                 return socket(domain, type, protocol);
147         }
148
149 #ifdef HAVE_SETNS
150         struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
151
152         pthread_t thr;
153
154         if(pthread_create(&thr, NULL, socket_in_netns_thread, &params) == 0) {
155                 pthread_join(thr, NULL);
156         }
157
158         return params.fd;
159 #else
160         return -1;
161 #endif // HAVE_SETNS
162
163 }
164
165 // Find out what local address a socket would use if we connect to the given address.
166 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
167 // of both endpoints, but this will actually not send any UDP packet.
168 static bool getlocaladdr(char *destaddr, sockaddr_t *sa, socklen_t *salen, int netns) {
169         struct addrinfo *rai = NULL;
170         const struct addrinfo hint = {
171                 .ai_family = AF_UNSPEC,
172                 .ai_socktype = SOCK_DGRAM,
173                 .ai_protocol = IPPROTO_UDP,
174         };
175
176         if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
177                 return false;
178         }
179
180         int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
181
182         if(sock == -1) {
183                 freeaddrinfo(rai);
184                 return false;
185         }
186
187         if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
188                 closesocket(sock);
189                 freeaddrinfo(rai);
190                 return false;
191         }
192
193         freeaddrinfo(rai);
194
195         if(getsockname(sock, &sa->sa, salen)) {
196                 closesocket(sock);
197                 return false;
198         }
199
200         closesocket(sock);
201         return true;
202 }
203
204 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
205         sockaddr_t sa;
206         socklen_t salen = sizeof(sa);
207
208         if(!getlocaladdr(destaddr, &sa, &salen, netns)) {
209                 return false;
210         }
211
212         if(getnameinfo(&sa.sa, salen, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
213                 return false;
214         }
215
216         return true;
217 }
218
219 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
220         return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
221 }
222
223 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
224         char *hostname = NULL;
225
226         logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
227         struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
228         static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
229         char line[256];
230
231         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
232                 if(family != AF_UNSPEC && aip->ai_family != family) {
233                         continue;
234                 }
235
236                 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
237
238                 if(s >= 0) {
239                         set_timeout(s, 5000);
240
241                         if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
242                                 closesocket(s);
243                                 s = -1;
244                         }
245                 }
246
247                 if(s >= 0) {
248                         send(s, request, sizeof(request) - 1, 0);
249                         int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
250
251                         if(len > 0) {
252                                 line[len] = 0;
253
254                                 if(line[len - 1] == '\n') {
255                                         line[--len] = 0;
256                                 }
257
258                                 char *p = strrchr(line, '\n');
259
260                                 if(p && p[1]) {
261                                         hostname = xstrdup(p + 1);
262                                 }
263                         }
264
265                         closesocket(s);
266
267                         if(hostname) {
268                                 break;
269                         }
270                 }
271         }
272
273         if(ai) {
274                 freeaddrinfo(ai);
275         }
276
277         // Check that the hostname is reasonable
278         if(hostname && !is_valid_hostname(hostname)) {
279                 free(hostname);
280                 hostname = NULL;
281         }
282
283         if(!hostname) {
284                 meshlink_errno = MESHLINK_ERESOLV;
285         }
286
287         return hostname;
288 }
289
290 static bool is_localaddr(sockaddr_t *sa) {
291         switch(sa->sa.sa_family) {
292         case AF_INET:
293                 return *(uint8_t *)(&sa->in.sin_addr.s_addr) == 127;
294
295         case AF_INET6: {
296                 uint16_t first = sa->in6.sin6_addr.s6_addr[0] << 8 | sa->in6.sin6_addr.s6_addr[1];
297                 return first == 0 || (first & 0xffc0) == 0xfe80;
298         }
299
300         default:
301                 return false;
302         }
303 }
304
305 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
306         (void)mesh;
307
308         // Determine address of the local interface used for outgoing connections.
309         char localaddr[NI_MAXHOST];
310         bool success = false;
311
312         if(family == AF_INET) {
313                 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
314         } else if(family == AF_INET6) {
315                 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
316         }
317
318 #ifdef HAVE_GETIFADDRS
319
320         if(!success) {
321                 struct ifaddrs *ifa = NULL;
322                 getifaddrs(&ifa);
323
324                 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
325                         sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
326
327                         if(sa->sa.sa_family != family) {
328                                 continue;
329                         }
330
331                         if(is_localaddr(sa)) {
332                                 continue;
333                         }
334
335                         if(!getnameinfo(&sa->sa, SALEN(sa->sa), localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
336                                 success = true;
337                                 break;
338                         }
339                 }
340
341                 freeifaddrs(ifa);
342         }
343
344 #endif
345
346         if(!success) {
347                 meshlink_errno = MESHLINK_ENETWORK;
348                 return NULL;
349         }
350
351         return xstrdup(localaddr);
352 }
353
354 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
355         for(int i = 0; i < n; i++) {
356                 if(!host[i]) {
357                         continue;
358                 }
359
360                 // Ignore duplicate hostnames
361                 bool found = false;
362
363                 for(int j = 0; j < i; j++) {
364                         if(!host[j]) {
365                                 continue;
366                         }
367
368                         if(strcmp(host[i], host[j])) {
369                                 continue;
370                         }
371
372                         if(strcmp(port[i], port[j])) {
373                                 continue;
374                         }
375
376                         found = true;
377                         break;
378                 }
379
380                 if(found || !is_valid_hostname(host[i])) {
381                         free(host[i]);
382                         free(port[i]);
383                         host[i] = NULL;
384                         port[i] = NULL;
385                         continue;
386                 }
387         }
388 }
389
390 // This gets the hostname part for use in invitation URLs
391 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
392         char *hostname[4] = {NULL};
393         char *port[4] = {NULL};
394         char *hostport = NULL;
395
396         if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
397                 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
398         }
399
400         if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
401                 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
402         }
403
404         // Add local addresses if requested
405         if(flags & MESHLINK_INVITE_LOCAL) {
406                 if(flags & MESHLINK_INVITE_IPV4) {
407                         hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
408                 }
409
410                 if(flags & MESHLINK_INVITE_IPV6) {
411                         hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
412                 }
413         }
414
415         // Add public/canonical addresses if requested
416         if(flags & MESHLINK_INVITE_PUBLIC) {
417                 // Try the CanonicalAddress first
418                 get_canonical_address(mesh->self, &hostname[2], &port[2]);
419
420                 if(!hostname[2]) {
421                         if(flags & MESHLINK_INVITE_IPV4) {
422                                 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
423                         }
424
425                         if(flags & MESHLINK_INVITE_IPV6) {
426                                 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
427                         }
428                 }
429         }
430
431         for(int i = 0; i < 4; i++) {
432                 // Ensure we always have a port number
433                 if(hostname[i] && !port[i]) {
434                         port[i] = xstrdup(mesh->myport);
435                 }
436         }
437
438         remove_duplicate_hostnames(hostname, port, 4);
439
440         // Resolve the hostnames
441         for(int i = 0; i < 4; i++) {
442                 if(!hostname[i]) {
443                         continue;
444                 }
445
446                 // Convert what we have to a sockaddr
447                 struct addrinfo *ai_in, *ai_out;
448                 struct addrinfo hint = {
449                         .ai_family = AF_UNSPEC,
450                         .ai_flags = AI_NUMERICSERV,
451                         .ai_socktype = SOCK_STREAM,
452                 };
453                 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
454
455                 if(err || !ai_in) {
456                         continue;
457                 }
458
459                 // Remember the address
460                 node_add_recent_address(mesh, mesh->self, (sockaddr_t *)ai_in->ai_addr);
461
462                 if(flags & MESHLINK_INVITE_NUMERIC) {
463                         // We don't need to do any further conversion
464                         freeaddrinfo(ai_in);
465                         continue;
466                 }
467
468                 // Convert it to a hostname
469                 char resolved_host[NI_MAXHOST];
470                 char resolved_port[NI_MAXSERV];
471                 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
472
473                 if(err || !is_valid_hostname(resolved_host)) {
474                         freeaddrinfo(ai_in);
475                         continue;
476                 }
477
478                 // Convert the hostname back to a sockaddr
479                 hint.ai_family = ai_in->ai_family;
480                 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
481
482                 if(err || !ai_out) {
483                         freeaddrinfo(ai_in);
484                         continue;
485                 }
486
487                 // Check if it's still the same sockaddr
488                 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
489                         freeaddrinfo(ai_in);
490                         freeaddrinfo(ai_out);
491                         continue;
492                 }
493
494                 // Yes: replace the hostname with the resolved one
495                 free(hostname[i]);
496                 hostname[i] = xstrdup(resolved_host);
497
498                 freeaddrinfo(ai_in);
499                 freeaddrinfo(ai_out);
500         }
501
502         // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
503         remove_duplicate_hostnames(hostname, port, 4);
504
505         // Concatenate all unique address to the hostport string
506         for(int i = 0; i < 4; i++) {
507                 if(!hostname[i]) {
508                         continue;
509                 }
510
511                 // Append the address to the hostport string
512                 char *newhostport;
513                 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
514                 free(hostport);
515                 hostport = newhostport;
516
517                 free(hostname[i]);
518                 free(port[i]);
519         }
520
521         return hostport;
522 }
523
524 static bool try_bind(int port) {
525         struct addrinfo *ai = NULL;
526         struct addrinfo hint = {
527                 .ai_flags = AI_PASSIVE,
528                 .ai_family = AF_UNSPEC,
529                 .ai_socktype = SOCK_STREAM,
530                 .ai_protocol = IPPROTO_TCP,
531         };
532
533         char portstr[16];
534         snprintf(portstr, sizeof(portstr), "%d", port);
535
536         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
537                 return false;
538         }
539
540         //while(ai) {
541         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
542                 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
543
544                 if(!fd) {
545                         freeaddrinfo(ai);
546                         return false;
547                 }
548
549                 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
550                 closesocket(fd);
551
552                 if(result) {
553                         freeaddrinfo(ai);
554                         return false;
555                 }
556         }
557
558         freeaddrinfo(ai);
559         return true;
560 }
561
562 static int check_port(meshlink_handle_t *mesh) {
563         for(int i = 0; i < 1000; i++) {
564                 int port = 0x1000 + prng(mesh, 0x8000);
565
566                 if(try_bind(port)) {
567                         free(mesh->myport);
568                         xasprintf(&mesh->myport, "%d", port);
569                         return port;
570                 }
571         }
572
573         meshlink_errno = MESHLINK_ENETWORK;
574         logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
575         return 0;
576 }
577
578 static bool write_main_config_files(meshlink_handle_t *mesh) {
579         if(!mesh->confbase) {
580                 return true;
581         }
582
583         uint8_t buf[4096];
584
585         /* Write the main config file */
586         packmsg_output_t out = {buf, sizeof buf};
587
588         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
589         packmsg_add_str(&out, mesh->name);
590         packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
591         packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
592         packmsg_add_uint16(&out, atoi(mesh->myport));
593
594         if(!packmsg_output_ok(&out)) {
595                 return false;
596         }
597
598         config_t config = {buf, packmsg_output_size(&out, buf)};
599
600         if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
601                 return false;
602         }
603
604         /* Write our own host config file */
605         if(!node_write_config(mesh, mesh->self)) {
606                 return false;
607         }
608
609         return true;
610 }
611
612 static bool finalize_join(meshlink_handle_t *mesh, const void *buf, uint16_t len) {
613         packmsg_input_t in = {buf, len};
614         uint32_t version = packmsg_get_uint32(&in);
615
616         if(version != MESHLINK_INVITATION_VERSION) {
617                 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
618                 return false;
619         }
620
621         char *name = packmsg_get_str_dup(&in);
622         packmsg_skip_element(&in); /* submesh */
623         dev_class_t devclass = packmsg_get_int32(&in);
624         uint32_t count = packmsg_get_array(&in);
625
626         if(!name) {
627                 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
628                 return false;
629         }
630
631         if(!check_id(name)) {
632                 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
633                 free(name);
634                 return false;
635         }
636
637         if(!count) {
638                 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
639                 free(name);
640                 return false;
641         }
642
643         free(mesh->name);
644         free(mesh->self->name);
645         mesh->name = name;
646         mesh->self->name = xstrdup(name);
647         mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
648
649         // Initialize configuration directory
650         if(!config_init(mesh, "current")) {
651                 return false;
652         }
653
654         if(!write_main_config_files(mesh)) {
655                 return false;
656         }
657
658         // Write host config files
659         for(uint32_t i = 0; i < count; i++) {
660                 const void *data;
661                 uint32_t len = packmsg_get_bin_raw(&in, &data);
662
663                 if(!len) {
664                         logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
665                         return false;
666                 }
667
668                 packmsg_input_t in2 = {data, len};
669                 uint32_t version = packmsg_get_uint32(&in2);
670                 char *name = packmsg_get_str_dup(&in2);
671
672                 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
673                         free(name);
674                         packmsg_input_invalidate(&in);
675                         break;
676                 }
677
678                 if(!check_id(name)) {
679                         free(name);
680                         break;
681                 }
682
683                 if(!strcmp(name, mesh->name)) {
684                         logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
685                         free(name);
686                         meshlink_errno = MESHLINK_EPEER;
687                         return false;
688                 }
689
690                 node_t *n = new_node();
691                 n->name = name;
692
693                 config_t config = {data, len};
694
695                 if(!node_read_from_config(mesh, n, &config)) {
696                         free_node(n);
697                         logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
698                         meshlink_errno = MESHLINK_EPEER;
699                         return false;
700                 }
701
702                 if(i == 0) {
703                         /* The first host config file is of the inviter itself;
704                          * remember the address we are currently using for the invitation connection.
705                          */
706                         sockaddr_t sa;
707                         socklen_t salen = sizeof(sa);
708
709                         if(getpeername(mesh->sock, &sa.sa, &salen) == 0) {
710                                 node_add_recent_address(mesh, n, &sa);
711                         }
712                 }
713
714                 /* Clear the reachability times, since we ourself have never seen these nodes yet */
715                 n->last_reachable = 0;
716                 n->last_unreachable = 0;
717
718                 if(!node_write_config(mesh, n)) {
719                         free_node(n);
720                         return false;
721                 }
722
723                 node_add(mesh, n);
724         }
725
726         /* Ensure the configuration directory metadata is on disk */
727         if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
728                 return false;
729         }
730
731         sptps_send_record(&mesh->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
732
733         logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
734
735         return true;
736 }
737
738 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
739         (void)type;
740         meshlink_handle_t *mesh = handle;
741         const char *ptr = data;
742
743         while(len) {
744                 int result = send(mesh->sock, ptr, len, 0);
745
746                 if(result == -1 && errno == EINTR) {
747                         continue;
748                 } else if(result <= 0) {
749                         return false;
750                 }
751
752                 ptr += result;
753                 len -= result;
754         }
755
756         return true;
757 }
758
759 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
760         meshlink_handle_t *mesh = handle;
761
762         switch(type) {
763         case SPTPS_HANDSHAKE:
764                 return sptps_send_record(&mesh->sptps, 0, mesh->cookie, sizeof(mesh)->cookie);
765
766         case 0:
767                 return finalize_join(mesh, msg, len);
768
769         case 1:
770                 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
771                 shutdown(mesh->sock, SHUT_RDWR);
772                 mesh->success = true;
773                 break;
774
775         default:
776                 return false;
777         }
778
779         return true;
780 }
781
782 static bool recvline(meshlink_handle_t *mesh, size_t len) {
783         char *newline = NULL;
784
785         if(!mesh->sock) {
786                 abort();
787         }
788
789         while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
790                 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
791
792                 if(result == -1 && errno == EINTR) {
793                         continue;
794                 } else if(result <= 0) {
795                         return false;
796                 }
797
798                 mesh->blen += result;
799         }
800
801         if((size_t)(newline - mesh->buffer) >= len) {
802                 return false;
803         }
804
805         len = newline - mesh->buffer;
806
807         memcpy(mesh->line, mesh->buffer, len);
808         mesh->line[len] = 0;
809         memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
810         mesh->blen -= len + 1;
811
812         return true;
813 }
814
815 static bool sendline(int fd, char *format, ...) {
816         char buffer[4096];
817         char *p = buffer;
818         int blen = 0;
819         va_list ap;
820
821         va_start(ap, format);
822         blen = vsnprintf(buffer, sizeof(buffer), format, ap);
823         va_end(ap);
824
825         if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
826                 return false;
827         }
828
829         buffer[blen] = '\n';
830         blen++;
831
832         while(blen) {
833                 int result = send(fd, p, blen, MSG_NOSIGNAL);
834
835                 if(result == -1 && errno == EINTR) {
836                         continue;
837                 } else if(result <= 0) {
838                         return false;
839                 }
840
841                 p += result;
842                 blen -= result;
843         }
844
845         return true;
846 }
847
848 static const char *errstr[] = {
849         [MESHLINK_OK] = "No error",
850         [MESHLINK_EINVAL] = "Invalid argument",
851         [MESHLINK_ENOMEM] = "Out of memory",
852         [MESHLINK_ENOENT] = "No such node",
853         [MESHLINK_EEXIST] = "Node already exists",
854         [MESHLINK_EINTERNAL] = "Internal error",
855         [MESHLINK_ERESOLV] = "Could not resolve hostname",
856         [MESHLINK_ESTORAGE] = "Storage error",
857         [MESHLINK_ENETWORK] = "Network error",
858         [MESHLINK_EPEER] = "Error communicating with peer",
859         [MESHLINK_ENOTSUP] = "Operation not supported",
860         [MESHLINK_EBUSY] = "MeshLink instance already in use",
861         [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
862 };
863
864 const char *meshlink_strerror(meshlink_errno_t err) {
865         if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
866                 return "Invalid error code";
867         }
868
869         return errstr[err];
870 }
871
872 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
873         logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
874
875         mesh->private_key = ecdsa_generate();
876         mesh->invitation_key = ecdsa_generate();
877
878         if(!mesh->private_key || !mesh->invitation_key) {
879                 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
880                 meshlink_errno = MESHLINK_EINTERNAL;
881                 return false;
882         }
883
884         logger(mesh, MESHLINK_DEBUG, "Done.\n");
885
886         return true;
887 }
888
889 static struct timeval idle(event_loop_t *loop, void *data) {
890         (void)loop;
891         meshlink_handle_t *mesh = data;
892         struct timeval t, tmin = {3600, 0};
893
894         for splay_each(node_t, n, mesh->nodes) {
895                 if(!n->utcp) {
896                         continue;
897                 }
898
899                 t = utcp_timeout(n->utcp);
900
901                 if(timercmp(&t, &tmin, <)) {
902                         tmin = t;
903                 }
904         }
905
906         return tmin;
907 }
908
909 // Get our local address(es) by simulating connecting to an Internet host.
910 static void add_local_addresses(meshlink_handle_t *mesh) {
911         sockaddr_t sa;
912         sa.storage.ss_family = AF_UNKNOWN;
913         socklen_t salen = sizeof(sa);
914
915         // IPv4 example.org
916
917         if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
918                 sa.in.sin_port = ntohs(atoi(mesh->myport));
919                 node_add_recent_address(mesh, mesh->self, &sa);
920         }
921
922         // IPv6 example.org
923
924         salen = sizeof(sa);
925
926         if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
927                 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
928                 node_add_recent_address(mesh, mesh->self, &sa);
929         }
930 }
931
932 static bool meshlink_setup(meshlink_handle_t *mesh) {
933         if(!config_destroy(mesh->confbase, "new")) {
934                 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
935                 meshlink_errno = MESHLINK_ESTORAGE;
936                 return false;
937         }
938
939         if(!config_destroy(mesh->confbase, "old")) {
940                 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
941                 meshlink_errno = MESHLINK_ESTORAGE;
942                 return false;
943         }
944
945         if(!config_init(mesh, "current")) {
946                 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
947                 meshlink_errno = MESHLINK_ESTORAGE;
948                 return false;
949         }
950
951         if(!ecdsa_keygen(mesh)) {
952                 meshlink_errno = MESHLINK_EINTERNAL;
953                 return false;
954         }
955
956         if(check_port(mesh) == 0) {
957                 meshlink_errno = MESHLINK_ENETWORK;
958                 return false;
959         }
960
961         /* Create a node for ourself */
962
963         mesh->self = new_node();
964         mesh->self->name = xstrdup(mesh->name);
965         mesh->self->devclass = mesh->devclass;
966         mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
967         mesh->self->session_id = mesh->session_id;
968
969         if(!write_main_config_files(mesh)) {
970                 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
971                 meshlink_errno = MESHLINK_ESTORAGE;
972                 return false;
973         }
974
975         /* Ensure the configuration directory metadata is on disk */
976         if(!config_sync(mesh, "current")) {
977                 return false;
978         }
979
980         return true;
981 }
982
983 static bool meshlink_read_config(meshlink_handle_t *mesh) {
984         config_t config;
985
986         if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
987                 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
988                 return false;
989         }
990
991         packmsg_input_t in = {config.buf, config.len};
992         const void *private_key;
993         const void *invitation_key;
994
995         uint32_t version = packmsg_get_uint32(&in);
996         char *name = packmsg_get_str_dup(&in);
997         uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
998         uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
999         uint16_t myport = packmsg_get_uint16(&in);
1000
1001         if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
1002                 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
1003                 free(name);
1004                 config_free(&config);
1005                 return false;
1006         }
1007
1008 #if 0
1009
1010         // TODO: check this?
1011         if(mesh->name && strcmp(mesh->name, name)) {
1012                 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
1013                 meshlink_errno = MESHLINK_ESTORAGE;
1014                 free(name);
1015                 config_free(&config);
1016                 return false;
1017         }
1018
1019 #endif
1020
1021         free(mesh->name);
1022         mesh->name = name;
1023         xasprintf(&mesh->myport, "%u", myport);
1024         mesh->private_key = ecdsa_set_private_key(private_key);
1025         mesh->invitation_key = ecdsa_set_private_key(invitation_key);
1026         config_free(&config);
1027
1028         /* Create a node for ourself and read our host configuration file */
1029
1030         mesh->self = new_node();
1031         mesh->self->name = xstrdup(name);
1032         mesh->self->devclass = mesh->devclass;
1033         mesh->self->session_id = mesh->session_id;
1034
1035         if(!node_read_public_key(mesh, mesh->self)) {
1036                 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1037                 meshlink_errno = MESHLINK_ESTORAGE;
1038                 free_node(mesh->self);
1039                 mesh->self = NULL;
1040                 return false;
1041         }
1042
1043         return true;
1044 }
1045
1046 #ifdef HAVE_SETNS
1047 static void *setup_network_in_netns_thread(void *arg) {
1048         meshlink_handle_t *mesh = arg;
1049
1050         if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1051                 return NULL;
1052         }
1053
1054         bool success = setup_network(mesh);
1055         add_local_addresses(mesh);
1056         return success ? arg : NULL;
1057 }
1058 #endif // HAVE_SETNS
1059
1060 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1061         if(!confbase || !*confbase) {
1062                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1063                 meshlink_errno = MESHLINK_EINVAL;
1064                 return NULL;
1065         }
1066
1067         if(!appname || !*appname) {
1068                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1069                 meshlink_errno = MESHLINK_EINVAL;
1070                 return NULL;
1071         }
1072
1073         if(strchr(appname, ' ')) {
1074                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1075                 meshlink_errno = MESHLINK_EINVAL;
1076                 return NULL;
1077         }
1078
1079         if(!name || !*name) {
1080                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1081                 meshlink_errno = MESHLINK_EINVAL;
1082                 return NULL;
1083         };
1084
1085         if(!check_id(name)) {
1086                 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1087                 meshlink_errno = MESHLINK_EINVAL;
1088                 return NULL;
1089         }
1090
1091         if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1092                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1093                 meshlink_errno = MESHLINK_EINVAL;
1094                 return NULL;
1095         }
1096
1097         meshlink_open_params_t *params = xzalloc(sizeof * params);
1098
1099         params->confbase = xstrdup(confbase);
1100         params->name = xstrdup(name);
1101         params->appname = xstrdup(appname);
1102         params->devclass = devclass;
1103         params->netns = -1;
1104
1105         return params;
1106 }
1107
1108 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1109         if(!params) {
1110                 meshlink_errno = MESHLINK_EINVAL;
1111                 return false;
1112         }
1113
1114         params->netns = netns;
1115
1116         return true;
1117 }
1118
1119 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1120         if(!params) {
1121                 meshlink_errno = MESHLINK_EINVAL;
1122                 return false;
1123         }
1124
1125         if((!key && keylen) || (key && !keylen)) {
1126                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1127                 meshlink_errno = MESHLINK_EINVAL;
1128                 return false;
1129         }
1130
1131         params->key = key;
1132         params->keylen = keylen;
1133
1134         return true;
1135 }
1136
1137 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1138         if(!mesh || !new_key || !new_keylen) {
1139                 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1140                 meshlink_errno = MESHLINK_EINVAL;
1141                 return false;
1142         }
1143
1144         pthread_mutex_lock(&mesh->mutex);
1145
1146         // Create hash for the new key
1147         void *new_config_key;
1148         new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1149
1150         if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1151                 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1152                 meshlink_errno = MESHLINK_EINTERNAL;
1153                 pthread_mutex_unlock(&mesh->mutex);
1154                 return false;
1155         }
1156
1157         // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1158
1159         if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1160                 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1161                 meshlink_errno = MESHLINK_ESTORAGE;
1162                 pthread_mutex_unlock(&mesh->mutex);
1163                 return false;
1164         }
1165
1166         devtool_keyrotate_probe(1);
1167
1168         // Rename confbase/current/ to confbase/old
1169
1170         if(!config_rename(mesh, "current", "old")) {
1171                 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1172                 meshlink_errno = MESHLINK_ESTORAGE;
1173                 pthread_mutex_unlock(&mesh->mutex);
1174                 return false;
1175         }
1176
1177         devtool_keyrotate_probe(2);
1178
1179         // Rename confbase/new/ to confbase/current
1180
1181         if(!config_rename(mesh, "new", "current")) {
1182                 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1183                 meshlink_errno = MESHLINK_ESTORAGE;
1184                 pthread_mutex_unlock(&mesh->mutex);
1185                 return false;
1186         }
1187
1188         devtool_keyrotate_probe(3);
1189
1190         // Cleanup the "old" confbase sub-directory
1191
1192         if(!config_destroy(mesh->confbase, "old")) {
1193                 pthread_mutex_unlock(&mesh->mutex);
1194                 return false;
1195         }
1196
1197         // Change the mesh handle key with new key
1198
1199         free(mesh->config_key);
1200         mesh->config_key = new_config_key;
1201
1202         pthread_mutex_unlock(&mesh->mutex);
1203
1204         return true;
1205 }
1206
1207 void meshlink_open_params_free(meshlink_open_params_t *params) {
1208         if(!params) {
1209                 meshlink_errno = MESHLINK_EINVAL;
1210                 return;
1211         }
1212
1213         free(params->confbase);
1214         free(params->name);
1215         free(params->appname);
1216
1217         free(params);
1218 }
1219
1220 /// Device class traits
1221 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1222         { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1223         { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
1224         { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 },     // DEV_CLASS_PORTABLE
1225         { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 },     // DEV_CLASS_UNKNOWN
1226 };
1227
1228 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1229         if(!confbase || !*confbase) {
1230                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1231                 meshlink_errno = MESHLINK_EINVAL;
1232                 return NULL;
1233         }
1234
1235         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1236         meshlink_open_params_t params;
1237         memset(&params, 0, sizeof(params));
1238
1239         params.confbase = (char *)confbase;
1240         params.name = (char *)name;
1241         params.appname = (char *)appname;
1242         params.devclass = devclass;
1243         params.netns = -1;
1244
1245         return meshlink_open_ex(&params);
1246 }
1247
1248 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) {
1249         if(!confbase || !*confbase) {
1250                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1251                 meshlink_errno = MESHLINK_EINVAL;
1252                 return NULL;
1253         }
1254
1255         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1256         meshlink_open_params_t params;
1257         memset(&params, 0, sizeof(params));
1258
1259         params.confbase = (char *)confbase;
1260         params.name = (char *)name;
1261         params.appname = (char *)appname;
1262         params.devclass = devclass;
1263         params.netns = -1;
1264
1265         if(!meshlink_open_params_set_storage_key(&params, key, keylen)) {
1266                 return false;
1267         }
1268
1269         return meshlink_open_ex(&params);
1270 }
1271
1272 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1273         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1274         meshlink_open_params_t params;
1275         memset(&params, 0, sizeof(params));
1276
1277         params.name = (char *)name;
1278         params.appname = (char *)appname;
1279         params.devclass = devclass;
1280         params.netns = -1;
1281
1282         return meshlink_open_ex(&params);
1283 }
1284
1285 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1286         // Validate arguments provided by the application
1287         bool usingname = false;
1288
1289         logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1290
1291         if(!params->appname || !*params->appname) {
1292                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1293                 meshlink_errno = MESHLINK_EINVAL;
1294                 return NULL;
1295         }
1296
1297         if(strchr(params->appname, ' ')) {
1298                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1299                 meshlink_errno = MESHLINK_EINVAL;
1300                 return NULL;
1301         }
1302
1303         if(!params->name || !*params->name) {
1304                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1305                 //return NULL;
1306         } else { //check name only if there is a name != NULL
1307
1308                 if(!check_id(params->name)) {
1309                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1310                         meshlink_errno = MESHLINK_EINVAL;
1311                         return NULL;
1312                 } else {
1313                         usingname = true;
1314                 }
1315         }
1316
1317         if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1318                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1319                 meshlink_errno = MESHLINK_EINVAL;
1320                 return NULL;
1321         }
1322
1323         if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1324                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1325                 meshlink_errno = MESHLINK_EINVAL;
1326                 return NULL;
1327         }
1328
1329         meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1330
1331         if(params->confbase) {
1332                 mesh->confbase = xstrdup(params->confbase);
1333         }
1334
1335         mesh->appname = xstrdup(params->appname);
1336         mesh->devclass = params->devclass;
1337         mesh->discovery = true;
1338         mesh->invitation_timeout = 604800; // 1 week
1339         mesh->netns = params->netns;
1340         mesh->submeshes = NULL;
1341         mesh->log_cb = global_log_cb;
1342         mesh->log_level = global_log_level;
1343
1344         randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1345
1346         do {
1347                 randomize(&mesh->session_id, sizeof(mesh->session_id));
1348         } while(mesh->session_id == 0);
1349
1350         memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1351
1352         if(usingname) {
1353                 mesh->name = xstrdup(params->name);
1354         }
1355
1356         // Hash the key
1357         if(params->key) {
1358                 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1359
1360                 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1361                         logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1362                         meshlink_close(mesh);
1363                         meshlink_errno = MESHLINK_EINTERNAL;
1364                         return NULL;
1365                 }
1366         }
1367
1368         // initialize mutex
1369         pthread_mutexattr_t attr;
1370         pthread_mutexattr_init(&attr);
1371         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1372         pthread_mutex_init(&mesh->mutex, &attr);
1373
1374         mesh->threadstarted = false;
1375         event_loop_init(&mesh->loop);
1376         mesh->loop.data = mesh;
1377
1378         meshlink_queue_init(&mesh->outpacketqueue);
1379
1380         // Atomically lock the configuration directory.
1381         if(!main_config_lock(mesh)) {
1382                 meshlink_close(mesh);
1383                 return NULL;
1384         }
1385
1386         // If no configuration exists yet, create it.
1387
1388         if(!meshlink_confbase_exists(mesh)) {
1389                 if(!meshlink_setup(mesh)) {
1390                         logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1391                         meshlink_close(mesh);
1392                         return NULL;
1393                 }
1394         } else {
1395                 if(!meshlink_read_config(mesh)) {
1396                         logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1397                         meshlink_close(mesh);
1398                         return NULL;
1399                 }
1400         }
1401
1402 #ifdef HAVE_MINGW
1403         struct WSAData wsa_state;
1404         WSAStartup(MAKEWORD(2, 2), &wsa_state);
1405 #endif
1406
1407         // Setup up everything
1408         // TODO: we should not open listening sockets yet
1409
1410         bool success = false;
1411
1412         if(mesh->netns != -1) {
1413 #ifdef HAVE_SETNS
1414                 pthread_t thr;
1415
1416                 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1417                         void *retval = NULL;
1418                         success = pthread_join(thr, &retval) == 0 && retval;
1419                 }
1420
1421 #else
1422                 meshlink_errno = MESHLINK_EINTERNAL;
1423                 return NULL;
1424
1425 #endif // HAVE_SETNS
1426         } else {
1427                 success = setup_network(mesh);
1428                 add_local_addresses(mesh);
1429         }
1430
1431         if(!success) {
1432                 meshlink_close(mesh);
1433                 meshlink_errno = MESHLINK_ENETWORK;
1434                 return NULL;
1435         }
1436
1437         add_local_addresses(mesh);
1438
1439         if(!node_write_config(mesh, mesh->self)) {
1440                 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1441                 return NULL;
1442         }
1443
1444         idle_set(&mesh->loop, idle, mesh);
1445
1446         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1447         return mesh;
1448 }
1449
1450 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t  *mesh, const char *submesh) {
1451         meshlink_submesh_t *s = NULL;
1452
1453         if(!mesh) {
1454                 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1455                 meshlink_errno = MESHLINK_EINVAL;
1456                 return NULL;
1457         }
1458
1459         if(!submesh || !*submesh) {
1460                 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1461                 meshlink_errno = MESHLINK_EINVAL;
1462                 return NULL;
1463         }
1464
1465         //lock mesh->nodes
1466         pthread_mutex_lock(&mesh->mutex);
1467
1468         s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1469
1470         pthread_mutex_unlock(&mesh->mutex);
1471
1472         return s;
1473 }
1474
1475 static void *meshlink_main_loop(void *arg) {
1476         meshlink_handle_t *mesh = arg;
1477
1478         if(mesh->netns != -1) {
1479 #ifdef HAVE_SETNS
1480
1481                 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1482                         pthread_cond_signal(&mesh->cond);
1483                         return NULL;
1484                 }
1485
1486 #else
1487                 pthread_cond_signal(&mesh->cond);
1488                 return NULL;
1489 #endif // HAVE_SETNS
1490         }
1491
1492 #if HAVE_CATTA
1493
1494         if(mesh->discovery) {
1495                 discovery_start(mesh);
1496         }
1497
1498 #endif
1499
1500         pthread_mutex_lock(&mesh->mutex);
1501
1502         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1503         pthread_cond_broadcast(&mesh->cond);
1504         main_loop(mesh);
1505         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1506
1507         pthread_mutex_unlock(&mesh->mutex);
1508
1509 #if HAVE_CATTA
1510
1511         // Stop discovery
1512         if(mesh->discovery) {
1513                 discovery_stop(mesh);
1514         }
1515
1516 #endif
1517
1518         return NULL;
1519 }
1520
1521 bool meshlink_start(meshlink_handle_t *mesh) {
1522         assert(mesh->self);
1523         assert(mesh->private_key);
1524
1525         if(!mesh) {
1526                 meshlink_errno = MESHLINK_EINVAL;
1527                 return false;
1528         }
1529
1530         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1531
1532         pthread_mutex_lock(&mesh->mutex);
1533
1534         assert(mesh->self->ecdsa);
1535         assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1536
1537         if(mesh->threadstarted) {
1538                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1539                 pthread_mutex_unlock(&mesh->mutex);
1540                 return true;
1541         }
1542
1543         if(mesh->listen_socket[0].tcp.fd < 0) {
1544                 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1545                 meshlink_errno = MESHLINK_ENETWORK;
1546                 return false;
1547         }
1548
1549         mesh->thedatalen = 0;
1550
1551         // TODO: open listening sockets first
1552
1553         //Check that a valid name is set
1554         if(!mesh->name) {
1555                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1556                 meshlink_errno = MESHLINK_EINVAL;
1557                 pthread_mutex_unlock(&mesh->mutex);
1558                 return false;
1559         }
1560
1561         init_outgoings(mesh);
1562
1563         // Start the main thread
1564
1565         event_loop_start(&mesh->loop);
1566
1567         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1568                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1569                 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1570                 meshlink_errno = MESHLINK_EINTERNAL;
1571                 event_loop_stop(&mesh->loop);
1572                 pthread_mutex_unlock(&mesh->mutex);
1573                 return false;
1574         }
1575
1576         pthread_cond_wait(&mesh->cond, &mesh->mutex);
1577         mesh->threadstarted = true;
1578
1579         // Ensure we are considered reachable
1580         graph(mesh);
1581
1582         pthread_mutex_unlock(&mesh->mutex);
1583         return true;
1584 }
1585
1586 void meshlink_stop(meshlink_handle_t *mesh) {
1587         if(!mesh) {
1588                 meshlink_errno = MESHLINK_EINVAL;
1589                 return;
1590         }
1591
1592         pthread_mutex_lock(&mesh->mutex);
1593         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1594
1595         // Shut down the main thread
1596         event_loop_stop(&mesh->loop);
1597
1598         // Send ourselves a UDP packet to kick the event loop
1599         for(int i = 0; i < mesh->listen_sockets; i++) {
1600                 sockaddr_t sa;
1601                 socklen_t salen = sizeof(sa);
1602
1603                 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1604                         logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1605                         continue;
1606                 }
1607
1608                 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1609                         logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1610                 }
1611         }
1612
1613         if(mesh->threadstarted) {
1614                 // Wait for the main thread to finish
1615                 pthread_mutex_unlock(&mesh->mutex);
1616                 pthread_join(mesh->thread, NULL);
1617                 pthread_mutex_lock(&mesh->mutex);
1618
1619                 mesh->threadstarted = false;
1620         }
1621
1622         // Close all metaconnections
1623         if(mesh->connections) {
1624                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1625                         next = node->next;
1626                         connection_t *c = node->data;
1627                         c->outgoing = NULL;
1628                         terminate_connection(mesh, c, false);
1629                 }
1630         }
1631
1632         exit_outgoings(mesh);
1633
1634         // Ensure we are considered unreachable
1635         if(mesh->nodes) {
1636                 graph(mesh);
1637         }
1638
1639         // Try to write out any changed node config files, ignore errors at this point.
1640         if(mesh->nodes) {
1641                 for splay_each(node_t, n, mesh->nodes) {
1642                         if(n->status.dirty) {
1643                                 n->status.dirty = !node_write_config(mesh, n);
1644                         }
1645                 }
1646         }
1647
1648         pthread_mutex_unlock(&mesh->mutex);
1649 }
1650
1651 void meshlink_close(meshlink_handle_t *mesh) {
1652         if(!mesh) {
1653                 meshlink_errno = MESHLINK_EINVAL;
1654                 return;
1655         }
1656
1657         // stop can be called even if mesh has not been started
1658         meshlink_stop(mesh);
1659
1660         // lock is not released after this
1661         pthread_mutex_lock(&mesh->mutex);
1662
1663         // Close and free all resources used.
1664
1665         close_network_connections(mesh);
1666
1667         logger(mesh, MESHLINK_INFO, "Terminating");
1668
1669         event_loop_exit(&mesh->loop);
1670
1671 #ifdef HAVE_MINGW
1672
1673         if(mesh->confbase) {
1674                 WSACleanup();
1675         }
1676
1677 #endif
1678
1679         ecdsa_free(mesh->invitation_key);
1680
1681         if(mesh->netns != -1) {
1682                 close(mesh->netns);
1683         }
1684
1685         for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1686                 free(packet);
1687         }
1688
1689         meshlink_queue_exit(&mesh->outpacketqueue);
1690
1691         free(mesh->name);
1692         free(mesh->appname);
1693         free(mesh->confbase);
1694         free(mesh->config_key);
1695         ecdsa_free(mesh->private_key);
1696
1697         main_config_unlock(mesh);
1698
1699         pthread_mutex_unlock(&mesh->mutex);
1700         pthread_mutex_destroy(&mesh->mutex);
1701
1702         memset(mesh, 0, sizeof(*mesh));
1703
1704         free(mesh);
1705 }
1706
1707 bool meshlink_destroy(const char *confbase) {
1708         if(!confbase) {
1709                 meshlink_errno = MESHLINK_EINVAL;
1710                 return false;
1711         }
1712
1713         /* Exit early if the confbase directory itself doesn't exist */
1714         if(access(confbase, F_OK) && errno == ENOENT) {
1715                 return true;
1716         }
1717
1718         /* Take the lock the same way meshlink_open() would. */
1719         char lockfilename[PATH_MAX];
1720         snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1721
1722         FILE *lockfile = fopen(lockfilename, "w+");
1723
1724         if(!lockfile) {
1725                 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1726                 meshlink_errno = MESHLINK_ESTORAGE;
1727                 return false;
1728         }
1729
1730 #ifdef FD_CLOEXEC
1731         fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1732 #endif
1733
1734 #ifdef HAVE_MINGW
1735         // TODO: use _locking()?
1736 #else
1737
1738         if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1739                 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1740                 fclose(lockfile);
1741                 meshlink_errno = MESHLINK_EBUSY;
1742                 return false;
1743         }
1744
1745 #endif
1746
1747         if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1748                 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1749                 return false;
1750         }
1751
1752         if(unlink(lockfilename)) {
1753                 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1754                 fclose(lockfile);
1755                 meshlink_errno = MESHLINK_ESTORAGE;
1756                 return false;
1757         }
1758
1759         fclose(lockfile);
1760
1761         if(!sync_path(confbase)) {
1762                 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1763                 meshlink_errno = MESHLINK_ESTORAGE;
1764                 return false;
1765         }
1766
1767         return true;
1768 }
1769
1770 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1771         if(!mesh) {
1772                 meshlink_errno = MESHLINK_EINVAL;
1773                 return;
1774         }
1775
1776         pthread_mutex_lock(&mesh->mutex);
1777         mesh->receive_cb = cb;
1778         pthread_mutex_unlock(&mesh->mutex);
1779 }
1780
1781 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1782         if(!mesh) {
1783                 meshlink_errno = MESHLINK_EINVAL;
1784                 return;
1785         }
1786
1787         pthread_mutex_lock(&mesh->mutex);
1788         mesh->connection_try_cb = cb;
1789         pthread_mutex_unlock(&mesh->mutex);
1790 }
1791
1792 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1793         if(!mesh) {
1794                 meshlink_errno = MESHLINK_EINVAL;
1795                 return;
1796         }
1797
1798         pthread_mutex_lock(&mesh->mutex);
1799         mesh->node_status_cb = cb;
1800         pthread_mutex_unlock(&mesh->mutex);
1801 }
1802
1803 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1804         if(!mesh) {
1805                 meshlink_errno = MESHLINK_EINVAL;
1806                 return;
1807         }
1808
1809         pthread_mutex_lock(&mesh->mutex);
1810         mesh->node_pmtu_cb = cb;
1811         pthread_mutex_unlock(&mesh->mutex);
1812 }
1813
1814 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1815         if(!mesh) {
1816                 meshlink_errno = MESHLINK_EINVAL;
1817                 return;
1818         }
1819
1820         pthread_mutex_lock(&mesh->mutex);
1821         mesh->node_duplicate_cb = cb;
1822         pthread_mutex_unlock(&mesh->mutex);
1823 }
1824
1825 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1826         if(mesh) {
1827                 pthread_mutex_lock(&mesh->mutex);
1828                 mesh->log_cb = cb;
1829                 mesh->log_level = cb ? level : 0;
1830                 pthread_mutex_unlock(&mesh->mutex);
1831         } else {
1832                 global_log_cb = cb;
1833                 global_log_level = cb ? level : 0;
1834         }
1835 }
1836
1837 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1838         if(!mesh) {
1839                 meshlink_errno = MESHLINK_EINVAL;
1840                 return;
1841         }
1842
1843         pthread_mutex_lock(&mesh->mutex);
1844         mesh->error_cb = cb;
1845         pthread_mutex_unlock(&mesh->mutex);
1846 }
1847
1848 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1849         meshlink_packethdr_t *hdr;
1850
1851         // Validate arguments
1852         if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1853                 meshlink_errno = MESHLINK_EINVAL;
1854                 return false;
1855         }
1856
1857         if(!len) {
1858                 return true;
1859         }
1860
1861         if(!data) {
1862                 meshlink_errno = MESHLINK_EINVAL;
1863                 return false;
1864         }
1865
1866         node_t *n = (node_t *)destination;
1867
1868         if(n->status.blacklisted) {
1869                 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1870                 meshlink_errno = MESHLINK_EBLACKLISTED;
1871                 return false;
1872         }
1873
1874         // Prepare the packet
1875         vpn_packet_t *packet = malloc(sizeof(*packet));
1876
1877         if(!packet) {
1878                 meshlink_errno = MESHLINK_ENOMEM;
1879                 return false;
1880         }
1881
1882         packet->probe = false;
1883         packet->tcp = false;
1884         packet->len = len + sizeof(*hdr);
1885
1886         hdr = (meshlink_packethdr_t *)packet->data;
1887         memset(hdr, 0, sizeof(*hdr));
1888         // leave the last byte as 0 to make sure strings are always
1889         // null-terminated if they are longer than the buffer
1890         strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1891         strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1892
1893         memcpy(packet->data + sizeof(*hdr), data, len);
1894
1895         // Queue it
1896         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1897                 free(packet);
1898                 meshlink_errno = MESHLINK_ENOMEM;
1899                 return false;
1900         }
1901
1902         // Notify event loop
1903         signal_trigger(&mesh->loop, &mesh->datafromapp);
1904
1905         return true;
1906 }
1907
1908 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1909         (void)loop;
1910         meshlink_handle_t *mesh = data;
1911         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1912
1913         if(!packet) {
1914                 return;
1915         }
1916
1917         mesh->self->in_packets++;
1918         mesh->self->in_bytes += packet->len;
1919         route(mesh, mesh->self, packet);
1920
1921         free(packet);
1922 }
1923
1924 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1925         if(!mesh || !destination) {
1926                 meshlink_errno = MESHLINK_EINVAL;
1927                 return -1;
1928         }
1929
1930         pthread_mutex_lock(&mesh->mutex);
1931
1932         node_t *n = (node_t *)destination;
1933
1934         if(!n->status.reachable) {
1935                 pthread_mutex_unlock(&mesh->mutex);
1936                 return 0;
1937
1938         } else if(n->mtuprobes > 30 && n->minmtu) {
1939                 pthread_mutex_unlock(&mesh->mutex);
1940                 return n->minmtu;
1941         } else {
1942                 pthread_mutex_unlock(&mesh->mutex);
1943                 return MTU;
1944         }
1945 }
1946
1947 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1948         if(!mesh || !node) {
1949                 meshlink_errno = MESHLINK_EINVAL;
1950                 return NULL;
1951         }
1952
1953         pthread_mutex_lock(&mesh->mutex);
1954
1955         node_t *n = (node_t *)node;
1956
1957         if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1958                 meshlink_errno = MESHLINK_EINTERNAL;
1959                 pthread_mutex_unlock(&mesh->mutex);
1960                 return false;
1961         }
1962
1963         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1964
1965         if(!fingerprint) {
1966                 meshlink_errno = MESHLINK_EINTERNAL;
1967         }
1968
1969         pthread_mutex_unlock(&mesh->mutex);
1970         return fingerprint;
1971 }
1972
1973 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1974         if(!mesh) {
1975                 meshlink_errno = MESHLINK_EINVAL;
1976                 return NULL;
1977         }
1978
1979         return (meshlink_node_t *)mesh->self;
1980 }
1981
1982 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1983         if(!mesh || !name) {
1984                 meshlink_errno = MESHLINK_EINVAL;
1985                 return NULL;
1986         }
1987
1988         node_t *n = NULL;
1989
1990         pthread_mutex_lock(&mesh->mutex);
1991         n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1992         pthread_mutex_unlock(&mesh->mutex);
1993
1994         if(!n) {
1995                 meshlink_errno = MESHLINK_ENOENT;
1996         }
1997
1998         return (meshlink_node_t *)n;
1999 }
2000
2001 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2002         if(!mesh || !name) {
2003                 meshlink_errno = MESHLINK_EINVAL;
2004                 return NULL;
2005         }
2006
2007         meshlink_submesh_t *submesh = NULL;
2008
2009         pthread_mutex_lock(&mesh->mutex);
2010         submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2011         pthread_mutex_unlock(&mesh->mutex);
2012
2013         if(!submesh) {
2014                 meshlink_errno = MESHLINK_ENOENT;
2015         }
2016
2017         return submesh;
2018 }
2019
2020 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2021         if(!mesh || !nmemb || (*nmemb && !nodes)) {
2022                 meshlink_errno = MESHLINK_EINVAL;
2023                 return NULL;
2024         }
2025
2026         meshlink_node_t **result;
2027
2028         //lock mesh->nodes
2029         pthread_mutex_lock(&mesh->mutex);
2030
2031         *nmemb = mesh->nodes->count;
2032         result = realloc(nodes, *nmemb * sizeof(*nodes));
2033
2034         if(result) {
2035                 meshlink_node_t **p = result;
2036
2037                 for splay_each(node_t, n, mesh->nodes) {
2038                         *p++ = (meshlink_node_t *)n;
2039                 }
2040         } else {
2041                 *nmemb = 0;
2042                 free(nodes);
2043                 meshlink_errno = MESHLINK_ENOMEM;
2044         }
2045
2046         pthread_mutex_unlock(&mesh->mutex);
2047
2048         return result;
2049 }
2050
2051 static meshlink_node_t **meshlink_get_all_nodes_by_condition(meshlink_handle_t *mesh, const void *condition, meshlink_node_t **nodes, size_t *nmemb, search_node_by_condition_t search_node) {
2052         meshlink_node_t **result;
2053
2054         pthread_mutex_lock(&mesh->mutex);
2055
2056         *nmemb = 0;
2057
2058         for splay_each(node_t, n, mesh->nodes) {
2059                 if(search_node(n, condition)) {
2060                         ++*nmemb;
2061                 }
2062         }
2063
2064         if(*nmemb == 0) {
2065                 free(nodes);
2066                 pthread_mutex_unlock(&mesh->mutex);
2067                 return NULL;
2068         }
2069
2070         result = realloc(nodes, *nmemb * sizeof(*nodes));
2071
2072         if(result) {
2073                 meshlink_node_t **p = result;
2074
2075                 for splay_each(node_t, n, mesh->nodes) {
2076                         if(search_node(n, condition)) {
2077                                 *p++ = (meshlink_node_t *)n;
2078                         }
2079                 }
2080         } else {
2081                 *nmemb = 0;
2082                 free(nodes);
2083                 meshlink_errno = MESHLINK_ENOMEM;
2084         }
2085
2086         pthread_mutex_unlock(&mesh->mutex);
2087
2088         return result;
2089 }
2090
2091 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2092         dev_class_t *devclass = (dev_class_t *)condition;
2093
2094         if(*devclass == (dev_class_t)node->devclass) {
2095                 return true;
2096         }
2097
2098         return false;
2099 }
2100
2101 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2102         if(condition == node->submesh) {
2103                 return true;
2104         }
2105
2106         return false;
2107 }
2108
2109 struct time_range {
2110         time_t start;
2111         time_t end;
2112 };
2113
2114 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2115         const struct time_range *range = condition;
2116         time_t start = node->last_reachable;
2117         time_t end = node->last_unreachable;
2118
2119         if(end < start) {
2120                 end = time(NULL);
2121
2122                 if(end < start) {
2123                         start = end;
2124                 }
2125         }
2126
2127         if(range->end >= range->start) {
2128                 return start <= range->end && end >= range->start;
2129         } else {
2130                 return start > range->start || end < range->end;
2131         }
2132 }
2133
2134 meshlink_node_t **meshlink_get_all_nodes_by_dev_class(meshlink_handle_t *mesh, dev_class_t devclass, meshlink_node_t **nodes, size_t *nmemb) {
2135         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2136                 meshlink_errno = MESHLINK_EINVAL;
2137                 return NULL;
2138         }
2139
2140         return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2141 }
2142
2143 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2144         if(!mesh || !submesh || !nmemb) {
2145                 meshlink_errno = MESHLINK_EINVAL;
2146                 return NULL;
2147         }
2148
2149         return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2150 }
2151
2152 meshlink_node_t **meshlink_get_all_nodes_by_last_reachable(meshlink_handle_t *mesh, time_t start, time_t end, meshlink_node_t **nodes, size_t *nmemb) {
2153         if(!mesh || !nmemb) {
2154                 meshlink_errno = MESHLINK_EINVAL;
2155                 return NULL;
2156         }
2157
2158         struct time_range range = {start, end};
2159
2160         return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2161 }
2162
2163 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2164         if(!mesh || !node) {
2165                 meshlink_errno = MESHLINK_EINVAL;
2166                 return -1;
2167         }
2168
2169         dev_class_t devclass;
2170
2171         pthread_mutex_lock(&mesh->mutex);
2172
2173         devclass = ((node_t *)node)->devclass;
2174
2175         pthread_mutex_unlock(&mesh->mutex);
2176
2177         return devclass;
2178 }
2179
2180 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2181         if(!mesh || !node) {
2182                 meshlink_errno = MESHLINK_EINVAL;
2183                 return NULL;
2184         }
2185
2186         node_t *n = (node_t *)node;
2187
2188         meshlink_submesh_t *s;
2189
2190         s = (meshlink_submesh_t *)n->submesh;
2191
2192         return s;
2193 }
2194
2195 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2196         if(!mesh || !node) {
2197                 meshlink_errno = MESHLINK_EINVAL;
2198                 return NULL;
2199         }
2200
2201         node_t *n = (node_t *)node;
2202         bool reachable;
2203
2204         pthread_mutex_lock(&mesh->mutex);
2205         reachable = n->status.reachable && !n->status.blacklisted;
2206
2207         if(last_reachable) {
2208                 *last_reachable = n->last_reachable;
2209         }
2210
2211         if(last_unreachable) {
2212                 *last_unreachable = n->last_unreachable;
2213         }
2214
2215         pthread_mutex_unlock(&mesh->mutex);
2216
2217         return reachable;
2218 }
2219
2220 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2221         if(!mesh || !data || !len || !signature || !siglen) {
2222                 meshlink_errno = MESHLINK_EINVAL;
2223                 return false;
2224         }
2225
2226         if(*siglen < MESHLINK_SIGLEN) {
2227                 meshlink_errno = MESHLINK_EINVAL;
2228                 return false;
2229         }
2230
2231         pthread_mutex_lock(&mesh->mutex);
2232
2233         if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2234                 meshlink_errno = MESHLINK_EINTERNAL;
2235                 pthread_mutex_unlock(&mesh->mutex);
2236                 return false;
2237         }
2238
2239         *siglen = MESHLINK_SIGLEN;
2240         pthread_mutex_unlock(&mesh->mutex);
2241         return true;
2242 }
2243
2244 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2245         if(!mesh || !data || !len || !signature) {
2246                 meshlink_errno = MESHLINK_EINVAL;
2247                 return false;
2248         }
2249
2250         if(siglen != MESHLINK_SIGLEN) {
2251                 meshlink_errno = MESHLINK_EINVAL;
2252                 return false;
2253         }
2254
2255         pthread_mutex_lock(&mesh->mutex);
2256
2257         bool rval = false;
2258
2259         struct node_t *n = (struct node_t *)source;
2260
2261         if(!node_read_public_key(mesh, n)) {
2262                 meshlink_errno = MESHLINK_EINTERNAL;
2263                 rval = false;
2264         } else {
2265                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2266         }
2267
2268         pthread_mutex_unlock(&mesh->mutex);
2269         return rval;
2270 }
2271
2272 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2273         pthread_mutex_lock(&mesh->mutex);
2274
2275         size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2276
2277         if(!count) {
2278                 // TODO: Update invitation key if necessary?
2279         }
2280
2281         pthread_mutex_unlock(&mesh->mutex);
2282
2283         return mesh->invitation_key;
2284 }
2285
2286 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2287         if(!mesh || !node || !address) {
2288                 meshlink_errno = MESHLINK_EINVAL;
2289                 return false;
2290         }
2291
2292         if(!is_valid_hostname(address)) {
2293                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2294                 meshlink_errno = MESHLINK_EINVAL;
2295                 return false;
2296         }
2297
2298         if(port && !is_valid_port(port)) {
2299                 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2300                 meshlink_errno = MESHLINK_EINVAL;
2301                 return false;
2302         }
2303
2304         char *canonical_address;
2305
2306         if(port) {
2307                 xasprintf(&canonical_address, "%s %s", address, port);
2308         } else {
2309                 canonical_address = xstrdup(address);
2310         }
2311
2312         pthread_mutex_lock(&mesh->mutex);
2313
2314         node_t *n = (node_t *)node;
2315         free(n->canonical_address);
2316         n->canonical_address = canonical_address;
2317
2318         if(!node_write_config(mesh, n)) {
2319                 pthread_mutex_unlock(&mesh->mutex);
2320                 return false;
2321         }
2322
2323         pthread_mutex_unlock(&mesh->mutex);
2324
2325         return config_sync(mesh, "current");
2326 }
2327
2328 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2329         return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2330 }
2331
2332 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2333         if(!mesh) {
2334                 meshlink_errno = MESHLINK_EINVAL;
2335                 return false;
2336         }
2337
2338         char *address = meshlink_get_external_address(mesh);
2339
2340         if(!address) {
2341                 return false;
2342         }
2343
2344         bool rval = meshlink_add_address(mesh, address);
2345         free(address);
2346
2347         return rval;
2348 }
2349
2350 int meshlink_get_port(meshlink_handle_t *mesh) {
2351         if(!mesh) {
2352                 meshlink_errno = MESHLINK_EINVAL;
2353                 return -1;
2354         }
2355
2356         if(!mesh->myport) {
2357                 meshlink_errno = MESHLINK_EINTERNAL;
2358                 return -1;
2359         }
2360
2361         int port;
2362
2363         pthread_mutex_lock(&mesh->mutex);
2364         port = atoi(mesh->myport);
2365         pthread_mutex_unlock(&mesh->mutex);
2366
2367         return port;
2368 }
2369
2370 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2371         if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2372                 meshlink_errno = MESHLINK_EINVAL;
2373                 return false;
2374         }
2375
2376         if(mesh->myport && port == atoi(mesh->myport)) {
2377                 return true;
2378         }
2379
2380         if(!try_bind(port)) {
2381                 meshlink_errno = MESHLINK_ENETWORK;
2382                 return false;
2383         }
2384
2385         devtool_trybind_probe();
2386
2387         bool rval = false;
2388
2389         pthread_mutex_lock(&mesh->mutex);
2390
2391         if(mesh->threadstarted) {
2392                 meshlink_errno = MESHLINK_EINVAL;
2393                 goto done;
2394         }
2395
2396         free(mesh->myport);
2397         xasprintf(&mesh->myport, "%d", port);
2398
2399         /* Close down the network. This also deletes mesh->self. */
2400         close_network_connections(mesh);
2401
2402         /* Recreate mesh->self. */
2403         mesh->self = new_node();
2404         mesh->self->name = xstrdup(mesh->name);
2405         mesh->self->devclass = mesh->devclass;
2406         mesh->self->session_id = mesh->session_id;
2407         xasprintf(&mesh->myport, "%d", port);
2408
2409         if(!node_read_public_key(mesh, mesh->self)) {
2410                 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2411                 meshlink_errno = MESHLINK_ESTORAGE;
2412                 free_node(mesh->self);
2413                 mesh->self = NULL;
2414                 goto done;
2415         } else if(!setup_network(mesh)) {
2416                 meshlink_errno = MESHLINK_ENETWORK;
2417                 goto done;
2418         }
2419
2420         /* Rebuild our own list of recent addresses */
2421         memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2422         add_local_addresses(mesh);
2423
2424         /* Write meshlink.conf with the updated port number */
2425         write_main_config_files(mesh);
2426
2427         rval = config_sync(mesh, "current");
2428
2429 done:
2430         pthread_mutex_unlock(&mesh->mutex);
2431
2432         return rval && meshlink_get_port(mesh) == port;
2433 }
2434
2435 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2436         mesh->invitation_timeout = timeout;
2437 }
2438
2439 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2440         meshlink_submesh_t *s = NULL;
2441
2442         if(!mesh) {
2443                 meshlink_errno = MESHLINK_EINVAL;
2444                 return NULL;
2445         }
2446
2447         if(submesh) {
2448                 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2449
2450                 if(s != submesh) {
2451                         logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2452                         meshlink_errno = MESHLINK_EINVAL;
2453                         return NULL;
2454                 }
2455         } else {
2456                 s = (meshlink_submesh_t *)mesh->self->submesh;
2457         }
2458
2459         pthread_mutex_lock(&mesh->mutex);
2460
2461         // Check validity of the new node's name
2462         if(!check_id(name)) {
2463                 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2464                 meshlink_errno = MESHLINK_EINVAL;
2465                 pthread_mutex_unlock(&mesh->mutex);
2466                 return NULL;
2467         }
2468
2469         // Ensure no host configuration file with that name exists
2470         if(config_exists(mesh, "current", name)) {
2471                 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2472                 meshlink_errno = MESHLINK_EEXIST;
2473                 pthread_mutex_unlock(&mesh->mutex);
2474                 return NULL;
2475         }
2476
2477         // Ensure no other nodes know about this name
2478         if(lookup_node(mesh, name)) {
2479                 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2480                 meshlink_errno = MESHLINK_EEXIST;
2481                 pthread_mutex_unlock(&mesh->mutex);
2482                 return NULL;
2483         }
2484
2485         // Get the local address
2486         char *address = get_my_hostname(mesh, flags);
2487
2488         if(!address) {
2489                 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2490                 meshlink_errno = MESHLINK_ERESOLV;
2491                 pthread_mutex_unlock(&mesh->mutex);
2492                 return NULL;
2493         }
2494
2495         if(!refresh_invitation_key(mesh)) {
2496                 meshlink_errno = MESHLINK_EINTERNAL;
2497                 pthread_mutex_unlock(&mesh->mutex);
2498                 return NULL;
2499         }
2500
2501         // If we changed our own host config file, write it out now
2502         if(mesh->self->status.dirty) {
2503                 if(!node_write_config(mesh, mesh->self)) {
2504                         logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
2505                         pthread_mutex_unlock(&mesh->mutex);
2506                         return NULL;
2507                 }
2508         }
2509
2510         char hash[64];
2511
2512         // Create a hash of the key.
2513         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2514         sha512(fingerprint, strlen(fingerprint), hash);
2515         b64encode_urlsafe(hash, hash, 18);
2516
2517         // Create a random cookie for this invitation.
2518         char cookie[25];
2519         randomize(cookie, 18);
2520
2521         // Create a filename that doesn't reveal the cookie itself
2522         char buf[18 + strlen(fingerprint)];
2523         char cookiehash[64];
2524         memcpy(buf, cookie, 18);
2525         memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2526         sha512(buf, sizeof(buf), cookiehash);
2527         b64encode_urlsafe(cookiehash, cookiehash, 18);
2528
2529         b64encode_urlsafe(cookie, cookie, 18);
2530
2531         free(fingerprint);
2532
2533         /* Construct the invitation file */
2534         uint8_t outbuf[4096];
2535         packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2536
2537         packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2538         packmsg_add_str(&inv, name);
2539         packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2540         packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2541
2542         /* TODO: Add several host config files to bootstrap connections.
2543          * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2544          * and are not blacklisted.
2545          */
2546         config_t configs[5];
2547         memset(configs, 0, sizeof(configs));
2548         int count = 0;
2549
2550         if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2551                 count++;
2552         }
2553
2554         /* Append host config files to the invitation file */
2555         packmsg_add_array(&inv, count);
2556
2557         for(int i = 0; i < count; i++) {
2558                 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2559                 config_free(&configs[i]);
2560         }
2561
2562         config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2563
2564         if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2565                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2566                 meshlink_errno = MESHLINK_ESTORAGE;
2567                 pthread_mutex_unlock(&mesh->mutex);
2568                 return NULL;
2569         }
2570
2571         // Create an URL from the local address, key hash and cookie
2572         char *url;
2573         xasprintf(&url, "%s/%s%s", address, hash, cookie);
2574         free(address);
2575
2576         pthread_mutex_unlock(&mesh->mutex);
2577         return url;
2578 }
2579
2580 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2581         return meshlink_invite_ex(mesh, submesh, name, 0);
2582 }
2583
2584 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2585         if(!mesh || !invitation) {
2586                 meshlink_errno = MESHLINK_EINVAL;
2587                 return false;
2588         }
2589
2590         pthread_mutex_lock(&mesh->mutex);
2591
2592         //Before doing meshlink_join make sure we are not connected to another mesh
2593         if(mesh->threadstarted) {
2594                 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2595                 meshlink_errno = MESHLINK_EINVAL;
2596                 pthread_mutex_unlock(&mesh->mutex);
2597                 return false;
2598         }
2599
2600         // Refuse to join a mesh if we are already part of one. We are part of one if we know at least one other node.
2601         if(mesh->nodes->count > 1) {
2602                 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2603                 meshlink_errno = MESHLINK_EINVAL;
2604                 pthread_mutex_unlock(&mesh->mutex);
2605                 return false;
2606         }
2607
2608         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2609         char copy[strlen(invitation) + 1];
2610         strcpy(copy, invitation);
2611
2612         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2613
2614         char *slash = strchr(copy, '/');
2615
2616         if(!slash) {
2617                 goto invalid;
2618         }
2619
2620         *slash++ = 0;
2621
2622         if(strlen(slash) != 48) {
2623                 goto invalid;
2624         }
2625
2626         char *address = copy;
2627         char *port = NULL;
2628
2629         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2630                 goto invalid;
2631         }
2632
2633         // Generate a throw-away key for the invitation.
2634         ecdsa_t *key = ecdsa_generate();
2635
2636         if(!key) {
2637                 meshlink_errno = MESHLINK_EINTERNAL;
2638                 pthread_mutex_unlock(&mesh->mutex);
2639                 return false;
2640         }
2641
2642         char *b64key = ecdsa_get_base64_public_key(key);
2643         char *comma;
2644         mesh->sock = -1;
2645
2646         while(address && *address) {
2647                 // We allow commas in the address part to support multiple addresses in one invitation URL.
2648                 comma = strchr(address, ',');
2649
2650                 if(comma) {
2651                         *comma++ = 0;
2652                 }
2653
2654                 // Split of the port
2655                 port = strrchr(address, ':');
2656
2657                 if(!port) {
2658                         goto invalid;
2659                 }
2660
2661                 *port++ = 0;
2662
2663                 // IPv6 address are enclosed in brackets, per RFC 3986
2664                 if(*address == '[') {
2665                         address++;
2666                         char *bracket = strchr(address, ']');
2667
2668                         if(!bracket) {
2669                                 goto invalid;
2670                         }
2671
2672                         *bracket++ = 0;
2673
2674                         if(*bracket) {
2675                                 goto invalid;
2676                         }
2677                 }
2678
2679                 // Connect to the meshlink daemon mentioned in the URL.
2680                 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2681
2682                 if(ai) {
2683                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2684                                 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2685
2686                                 if(mesh->sock == -1) {
2687                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2688                                         meshlink_errno = MESHLINK_ENETWORK;
2689                                         continue;
2690                                 }
2691
2692                                 set_timeout(mesh->sock, 5000);
2693
2694                                 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2695                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2696                                         meshlink_errno = MESHLINK_ENETWORK;
2697                                         closesocket(mesh->sock);
2698                                         mesh->sock = -1;
2699                                         continue;
2700                                 }
2701                         }
2702
2703                         freeaddrinfo(ai);
2704                 } else {
2705                         meshlink_errno = MESHLINK_ERESOLV;
2706                 }
2707
2708                 if(mesh->sock != -1 || !comma) {
2709                         break;
2710                 }
2711
2712                 address = comma;
2713         }
2714
2715         if(mesh->sock == -1) {
2716                 pthread_mutex_unlock(&mesh->mutex);
2717                 return false;
2718         }
2719
2720         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2721
2722         // Tell him we have an invitation, and give him our throw-away key.
2723
2724         mesh->blen = 0;
2725
2726         if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2727                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2728                 closesocket(mesh->sock);
2729                 meshlink_errno = MESHLINK_ENETWORK;
2730                 pthread_mutex_unlock(&mesh->mutex);
2731                 return false;
2732         }
2733
2734         free(b64key);
2735
2736         char hisname[4096] = "";
2737         int code, hismajor, hisminor = 0;
2738
2739         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) {
2740                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2741                 closesocket(mesh->sock);
2742                 meshlink_errno = MESHLINK_ENETWORK;
2743                 pthread_mutex_unlock(&mesh->mutex);
2744                 return false;
2745         }
2746
2747         // Check if the hash of the key he gave us matches the hash in the URL.
2748         char *fingerprint = mesh->line + 2;
2749         char hishash[64];
2750
2751         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2752                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2753                 meshlink_errno = MESHLINK_EINTERNAL;
2754                 pthread_mutex_unlock(&mesh->mutex);
2755                 return false;
2756         }
2757
2758         if(memcmp(hishash, mesh->hash, 18)) {
2759                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2760                 meshlink_errno = MESHLINK_EPEER;
2761                 pthread_mutex_unlock(&mesh->mutex);
2762                 return false;
2763
2764         }
2765
2766         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2767
2768         if(!hiskey) {
2769                 meshlink_errno = MESHLINK_EINTERNAL;
2770                 pthread_mutex_unlock(&mesh->mutex);
2771                 return false;
2772         }
2773
2774         // Start an SPTPS session
2775         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2776                 meshlink_errno = MESHLINK_EINTERNAL;
2777                 pthread_mutex_unlock(&mesh->mutex);
2778                 return false;
2779         }
2780
2781         // Feed rest of input buffer to SPTPS
2782         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2783                 meshlink_errno = MESHLINK_EPEER;
2784                 pthread_mutex_unlock(&mesh->mutex);
2785                 return false;
2786         }
2787
2788         int len;
2789
2790         while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2791                 if(len < 0) {
2792                         if(errno == EINTR) {
2793                                 continue;
2794                         }
2795
2796                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2797                         meshlink_errno = MESHLINK_ENETWORK;
2798                         pthread_mutex_unlock(&mesh->mutex);
2799                         return false;
2800                 }
2801
2802                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2803                         meshlink_errno = MESHLINK_EPEER;
2804                         pthread_mutex_unlock(&mesh->mutex);
2805                         return false;
2806                 }
2807         }
2808
2809         sptps_stop(&mesh->sptps);
2810         ecdsa_free(hiskey);
2811         ecdsa_free(key);
2812         closesocket(mesh->sock);
2813
2814         if(!mesh->success) {
2815                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2816                 meshlink_errno = MESHLINK_EPEER;
2817                 pthread_mutex_unlock(&mesh->mutex);
2818                 return false;
2819         }
2820
2821         pthread_mutex_unlock(&mesh->mutex);
2822         return true;
2823
2824 invalid:
2825         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2826         meshlink_errno = MESHLINK_EINVAL;
2827         pthread_mutex_unlock(&mesh->mutex);
2828         return false;
2829 }
2830
2831 char *meshlink_export(meshlink_handle_t *mesh) {
2832         if(!mesh) {
2833                 meshlink_errno = MESHLINK_EINVAL;
2834                 return NULL;
2835         }
2836
2837         // Create a config file on the fly.
2838
2839         uint8_t buf[4096];
2840         packmsg_output_t out = {buf, sizeof(buf)};
2841         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2842         packmsg_add_str(&out, mesh->name);
2843         packmsg_add_str(&out, CORE_MESH);
2844
2845         pthread_mutex_lock(&mesh->mutex);
2846
2847         packmsg_add_int32(&out, mesh->self->devclass);
2848         packmsg_add_bool(&out, mesh->self->status.blacklisted);
2849         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2850         packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2851
2852         uint32_t count = 0;
2853
2854         for(uint32_t i = 0; i < MAX_RECENT; i++) {
2855                 if(mesh->self->recent[i].sa.sa_family) {
2856                         count++;
2857                 } else {
2858                         break;
2859                 }
2860         }
2861
2862         packmsg_add_array(&out, count);
2863
2864         for(uint32_t i = 0; i < count; i++) {
2865                 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2866         }
2867
2868         packmsg_add_int64(&out, 0);
2869         packmsg_add_int64(&out, 0);
2870
2871         pthread_mutex_unlock(&mesh->mutex);
2872
2873         if(!packmsg_output_ok(&out)) {
2874                 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2875                 meshlink_errno = MESHLINK_EINTERNAL;
2876                 return NULL;
2877         }
2878
2879         // Prepare a base64-encoded packmsg array containing our config file
2880
2881         uint32_t len = packmsg_output_size(&out, buf);
2882         uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2883         uint8_t *buf2 = xmalloc(len2);
2884         packmsg_output_t out2 = {buf2, len2};
2885         packmsg_add_array(&out2, 1);
2886         packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2887
2888         if(!packmsg_output_ok(&out2)) {
2889                 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2890                 meshlink_errno = MESHLINK_EINTERNAL;
2891                 free(buf2);
2892                 return NULL;
2893         }
2894
2895         b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2896
2897         return (char *)buf2;
2898 }
2899
2900 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2901         if(!mesh || !data) {
2902                 meshlink_errno = MESHLINK_EINVAL;
2903                 return false;
2904         }
2905
2906         size_t datalen = strlen(data);
2907         uint8_t *buf = xmalloc(datalen);
2908         int buflen = b64decode(data, buf, datalen);
2909
2910         if(!buflen) {
2911                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2912                 meshlink_errno = MESHLINK_EPEER;
2913                 return false;
2914         }
2915
2916         packmsg_input_t in = {buf, buflen};
2917         uint32_t count = packmsg_get_array(&in);
2918
2919         if(!count) {
2920                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2921                 meshlink_errno = MESHLINK_EPEER;
2922                 return false;
2923         }
2924
2925         pthread_mutex_lock(&mesh->mutex);
2926
2927         while(count--) {
2928                 const void *data;
2929                 uint32_t len = packmsg_get_bin_raw(&in, &data);
2930
2931                 if(!len) {
2932                         break;
2933                 }
2934
2935                 packmsg_input_t in2 = {data, len};
2936                 uint32_t version = packmsg_get_uint32(&in2);
2937                 char *name = packmsg_get_str_dup(&in2);
2938
2939                 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2940                         free(name);
2941                         packmsg_input_invalidate(&in);
2942                         break;
2943                 }
2944
2945                 if(!check_id(name)) {
2946                         free(name);
2947                         break;
2948                 }
2949
2950                 node_t *n = lookup_node(mesh, name);
2951
2952                 if(n) {
2953                         logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2954                         free(name);
2955                         continue;
2956                 }
2957
2958                 n = new_node();
2959                 n->name = name;
2960
2961                 config_t config = {data, len};
2962
2963                 if(!node_read_from_config(mesh, n, &config)) {
2964                         free_node(n);
2965                         packmsg_input_invalidate(&in);
2966                         break;
2967                 }
2968
2969                 /* Clear the reachability times, since we ourself have never seen these nodes yet */
2970                 n->last_reachable = 0;
2971                 n->last_unreachable = 0;
2972
2973                 if(!node_write_config(mesh, n)) {
2974                         free_node(n);
2975                         return false;
2976                 }
2977
2978                 node_add(mesh, n);
2979         }
2980
2981         pthread_mutex_unlock(&mesh->mutex);
2982
2983         free(buf);
2984
2985         if(!packmsg_done(&in)) {
2986                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2987                 meshlink_errno = MESHLINK_EPEER;
2988                 return false;
2989         }
2990
2991         if(!config_sync(mesh, "current")) {
2992                 return false;
2993         }
2994
2995         return true;
2996 }
2997
2998 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
2999         if(n == mesh->self) {
3000                 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3001                 meshlink_errno = MESHLINK_EINVAL;
3002                 return false;
3003         }
3004
3005         if(n->status.blacklisted) {
3006                 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3007                 return true;
3008         }
3009
3010         n->status.blacklisted = true;
3011
3012         /* Immediately shut down any connections we have with the blacklisted node.
3013          * We can't call terminate_connection(), because we might be called from a callback function.
3014          */
3015         for list_each(connection_t, c, mesh->connections) {
3016                 if(c->node == n) {
3017                         shutdown(c->socket, SHUT_RDWR);
3018                 }
3019         }
3020
3021         utcp_abort_all_connections(n->utcp);
3022
3023         n->mtu = 0;
3024         n->minmtu = 0;
3025         n->maxmtu = MTU;
3026         n->mtuprobes = 0;
3027         n->status.udp_confirmed = false;
3028
3029         if(n->status.reachable) {
3030                 n->last_unreachable = mesh->loop.now.tv_sec;
3031         }
3032
3033         /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3034          * manually call the status callback if necessary.
3035          */
3036         if(n->status.reachable && mesh->node_status_cb) {
3037                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3038         }
3039
3040         return node_write_config(mesh, n) && config_sync(mesh, "current");
3041 }
3042
3043 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3044         if(!mesh || !node) {
3045                 meshlink_errno = MESHLINK_EINVAL;
3046                 return false;
3047         }
3048
3049         pthread_mutex_lock(&mesh->mutex);
3050
3051         if(!blacklist(mesh, (node_t *)node)) {
3052                 pthread_mutex_unlock(&mesh->mutex);
3053                 return false;
3054         }
3055
3056         pthread_mutex_unlock(&mesh->mutex);
3057
3058         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3059         return true;
3060 }
3061
3062 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3063         if(!mesh || !name) {
3064                 meshlink_errno = MESHLINK_EINVAL;
3065                 return false;
3066         }
3067
3068         pthread_mutex_lock(&mesh->mutex);
3069
3070         node_t *n = lookup_node(mesh, (char *)name);
3071
3072         if(!n) {
3073                 n = new_node();
3074                 n->name = xstrdup(name);
3075                 node_add(mesh, n);
3076         }
3077
3078         if(!blacklist(mesh, (node_t *)n)) {
3079                 pthread_mutex_unlock(&mesh->mutex);
3080                 return false;
3081         }
3082
3083         pthread_mutex_unlock(&mesh->mutex);
3084
3085         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3086         return true;
3087 }
3088
3089 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3090         if(n == mesh->self) {
3091                 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3092                 meshlink_errno = MESHLINK_EINVAL;
3093                 return false;
3094         }
3095
3096         if(!n->status.blacklisted) {
3097                 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3098                 return true;
3099         }
3100
3101         n->status.blacklisted = false;
3102
3103         if(n->status.reachable) {
3104                 n->last_reachable = mesh->loop.now.tv_sec;
3105                 update_node_status(mesh, n);
3106         }
3107
3108         return node_write_config(mesh, n) && config_sync(mesh, "current");
3109 }
3110
3111 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3112         if(!mesh || !node) {
3113                 meshlink_errno = MESHLINK_EINVAL;
3114                 return false;
3115         }
3116
3117         pthread_mutex_lock(&mesh->mutex);
3118
3119         if(!whitelist(mesh, (node_t *)node)) {
3120                 pthread_mutex_unlock(&mesh->mutex);
3121                 return false;
3122         }
3123
3124         pthread_mutex_unlock(&mesh->mutex);
3125
3126         logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3127         return true;
3128 }
3129
3130 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3131         if(!mesh || !name) {
3132                 meshlink_errno = MESHLINK_EINVAL;
3133                 return false;
3134         }
3135
3136         pthread_mutex_lock(&mesh->mutex);
3137
3138         node_t *n = lookup_node(mesh, (char *)name);
3139
3140         if(!n) {
3141                 n = new_node();
3142                 n->name = xstrdup(name);
3143                 node_add(mesh, n);
3144         }
3145
3146         if(!whitelist(mesh, (node_t *)n)) {
3147                 pthread_mutex_unlock(&mesh->mutex);
3148                 return false;
3149         }
3150
3151         pthread_mutex_unlock(&mesh->mutex);
3152
3153         logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3154         return true;
3155 }
3156
3157 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3158         mesh->default_blacklist = blacklist;
3159 }
3160
3161 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3162         if(!mesh || !node) {
3163                 meshlink_errno = MESHLINK_EINVAL;
3164                 return false;
3165         }
3166
3167         node_t *n = (node_t *)node;
3168
3169         pthread_mutex_lock(&mesh->mutex);
3170
3171         /* Check that the node is not reachable */
3172         if(n->status.reachable || n->connection) {
3173                 pthread_mutex_unlock(&mesh->mutex);
3174                 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3175                 return false;
3176         }
3177
3178         /* Check that we don't have any active UTCP connections */
3179         if(n->utcp && utcp_is_active(n->utcp)) {
3180                 pthread_mutex_unlock(&mesh->mutex);
3181                 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3182                 return false;
3183         }
3184
3185         /* Check that we have no active connections to this node */
3186         for list_each(connection_t, c, mesh->connections) {
3187                 if(c->node == n) {
3188                         pthread_mutex_unlock(&mesh->mutex);
3189                         logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3190                         return false;
3191                 }
3192         }
3193
3194         /* Remove any pending outgoings to this node */
3195         if(mesh->outgoings) {
3196                 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3197                         if(outgoing->node == n) {
3198                                 list_delete_node(mesh->outgoings, node);
3199                         }
3200                 }
3201         }
3202
3203         /* Delete the config file for this node */
3204         if(!config_delete(mesh, "current", n->name)) {
3205                 pthread_mutex_unlock(&mesh->mutex);
3206                 return false;
3207         }
3208
3209         /* Delete the node struct and any remaining edges referencing this node */
3210         node_del(mesh, n);
3211
3212         pthread_mutex_unlock(&mesh->mutex);
3213
3214         return config_sync(mesh, "current");
3215 }
3216
3217 /* Hint that a hostname may be found at an address
3218  * See header file for detailed comment.
3219  */
3220 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3221         if(!mesh || !node || !addr) {
3222                 meshlink_errno = EINVAL;
3223                 return;
3224         }
3225
3226         pthread_mutex_lock(&mesh->mutex);
3227
3228         node_t *n = (node_t *)node;
3229
3230         if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3231                 if(!node_write_config(mesh, n)) {
3232                         logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3233                 }
3234         }
3235
3236         pthread_mutex_unlock(&mesh->mutex);
3237         // @TODO do we want to fire off a connection attempt right away?
3238 }
3239
3240 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3241         (void)port;
3242         node_t *n = utcp->priv;
3243         meshlink_handle_t *mesh = n->mesh;
3244         return mesh->channel_accept_cb;
3245 }
3246
3247 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3248         if(aio->data) {
3249                 if(aio->cb.buffer) {
3250                         aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3251                 }
3252         } else {
3253                 if(aio->cb.fd) {
3254                         aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3255                 }
3256         }
3257 }
3258
3259 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3260         meshlink_channel_t *channel = connection->priv;
3261
3262         if(!channel) {
3263                 abort();
3264         }
3265
3266         node_t *n = channel->node;
3267         meshlink_handle_t *mesh = n->mesh;
3268
3269         if(n->status.destroyed) {
3270                 meshlink_channel_close(mesh, channel);
3271                 return len;
3272         }
3273
3274         const char *p = data;
3275         size_t left = len;
3276
3277         while(channel->aio_receive) {
3278                 meshlink_aio_buffer_t *aio = channel->aio_receive;
3279                 size_t todo = aio->len - aio->done;
3280
3281                 if(todo > left) {
3282                         todo = left;
3283                 }
3284
3285                 if(aio->data) {
3286                         memcpy((char *)aio->data + aio->done, p, todo);
3287                 } else {
3288                         ssize_t result = write(aio->fd, p, todo);
3289
3290                         if(result > 0) {
3291                                 todo = result;
3292                         }
3293                 }
3294
3295                 aio->done += todo;
3296
3297                 if(aio->done == aio->len) {
3298                         channel->aio_receive = aio->next;
3299                         aio_signal(mesh, channel, aio);
3300                         free(aio);
3301                 }
3302
3303                 p += todo;
3304                 left -= todo;
3305
3306                 if(!left && len) {
3307                         return len;
3308                 }
3309         }
3310
3311         if(channel->receive_cb) {
3312                 channel->receive_cb(mesh, channel, p, left);
3313         }
3314
3315         return len;
3316 }
3317
3318 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3319         node_t *n = utcp_connection->utcp->priv;
3320
3321         if(!n) {
3322                 abort();
3323         }
3324
3325         meshlink_handle_t *mesh = n->mesh;
3326
3327         if(!mesh->channel_accept_cb) {
3328                 return;
3329         }
3330
3331         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3332         channel->node = n;
3333         channel->c = utcp_connection;
3334
3335         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3336                 utcp_accept(utcp_connection, channel_recv, channel);
3337         } else {
3338                 free(channel);
3339         }
3340 }
3341
3342 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3343         node_t *n = utcp->priv;
3344
3345         if(n->status.destroyed) {
3346                 return -1;
3347         }
3348
3349         meshlink_handle_t *mesh = n->mesh;
3350         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3351 }
3352
3353 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3354         if(!mesh || !channel) {
3355                 meshlink_errno = MESHLINK_EINVAL;
3356                 return;
3357         }
3358
3359         channel->receive_cb = cb;
3360 }
3361
3362 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3363         (void)mesh;
3364         node_t *n = (node_t *)source;
3365
3366         if(!n->utcp) {
3367                 abort();
3368         }
3369
3370         utcp_recv(n->utcp, data, len);
3371 }
3372
3373 static void channel_poll(struct utcp_connection *connection, size_t len) {
3374         meshlink_channel_t *channel = connection->priv;
3375
3376         if(!channel) {
3377                 abort();
3378         }
3379
3380         node_t *n = channel->node;
3381         meshlink_handle_t *mesh = n->mesh;
3382         meshlink_aio_buffer_t *aio = channel->aio_send;
3383
3384         if(aio) {
3385                 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3386                 size_t left = aio->len - aio->done;
3387                 ssize_t sent;
3388
3389                 if(len > left) {
3390                         len = left;
3391                 }
3392
3393                 if(aio->data) {
3394                         sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3395                 } else {
3396                         char buf[65536];
3397                         size_t todo = utcp_get_sndbuf_free(connection);
3398
3399                         if(todo > left) {
3400                                 todo = left;
3401                         }
3402
3403                         if(todo > sizeof(buf)) {
3404                                 todo = sizeof(buf);
3405                         }
3406
3407                         ssize_t result = read(aio->fd, buf, todo);
3408
3409                         if(result > 0) {
3410                                 sent = utcp_send(connection, buf, result);
3411                         } else {
3412                                 sent = result;
3413                         }
3414                 }
3415
3416                 if(sent >= 0) {
3417                         aio->done += sent;
3418                 }
3419
3420                 /* If the buffer is now completely sent, call the callback and dispose of it. */
3421                 if(aio->done >= aio->len) {
3422                         channel->aio_send = aio->next;
3423                         aio_signal(mesh, channel, aio);
3424                         free(aio);
3425                 }
3426         } else {
3427                 if(channel->poll_cb) {
3428                         channel->poll_cb(mesh, channel, len);
3429                 } else {
3430                         utcp_set_poll_cb(connection, NULL);
3431                 }
3432         }
3433 }
3434
3435 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3436         if(!mesh || !channel) {
3437                 meshlink_errno = MESHLINK_EINVAL;
3438                 return;
3439         }
3440
3441         pthread_mutex_lock(&mesh->mutex);
3442         channel->poll_cb = cb;
3443         utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3444         pthread_mutex_unlock(&mesh->mutex);
3445 }
3446
3447 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3448         if(!mesh) {
3449                 meshlink_errno = MESHLINK_EINVAL;
3450                 return;
3451         }
3452
3453         pthread_mutex_lock(&mesh->mutex);
3454         mesh->channel_accept_cb = cb;
3455         mesh->receive_cb = channel_receive;
3456
3457         for splay_each(node_t, n, mesh->nodes) {
3458                 if(!n->utcp && n != mesh->self) {
3459                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3460                 }
3461         }
3462
3463         pthread_mutex_unlock(&mesh->mutex);
3464 }
3465
3466 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3467         (void)mesh;
3468
3469         if(!channel) {
3470                 meshlink_errno = MESHLINK_EINVAL;
3471                 return;
3472         }
3473
3474         pthread_mutex_lock(&mesh->mutex);
3475         utcp_set_sndbuf(channel->c, size);
3476         pthread_mutex_unlock(&mesh->mutex);
3477 }
3478
3479 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3480         (void)mesh;
3481
3482         if(!channel) {
3483                 meshlink_errno = MESHLINK_EINVAL;
3484                 return;
3485         }
3486
3487         pthread_mutex_lock(&mesh->mutex);
3488         utcp_set_rcvbuf(channel->c, size);
3489         pthread_mutex_unlock(&mesh->mutex);
3490 }
3491
3492 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) {
3493         if(data && len) {
3494                 abort();        // TODO: handle non-NULL data
3495         }
3496
3497         if(!mesh || !node) {
3498                 meshlink_errno = MESHLINK_EINVAL;
3499                 return NULL;
3500         }
3501
3502         pthread_mutex_lock(&mesh->mutex);
3503
3504         node_t *n = (node_t *)node;
3505
3506         if(!n->utcp) {
3507                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3508                 mesh->receive_cb = channel_receive;
3509
3510                 if(!n->utcp) {
3511                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3512                         pthread_mutex_unlock(&mesh->mutex);
3513                         return NULL;
3514                 }
3515         }
3516
3517         if(n->status.blacklisted) {
3518                 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3519                 meshlink_errno = MESHLINK_EBLACKLISTED;
3520                 pthread_mutex_unlock(&mesh->mutex);
3521                 return NULL;
3522         }
3523
3524         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3525         channel->node = n;
3526         channel->receive_cb = cb;
3527
3528         if(data && !len) {
3529                 channel->priv = (void *)data;
3530         }
3531
3532         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3533
3534         pthread_mutex_unlock(&mesh->mutex);
3535
3536         if(!channel->c) {
3537                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3538                 free(channel);
3539                 return NULL;
3540         }
3541
3542         return channel;
3543 }
3544
3545 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) {
3546         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3547 }
3548
3549 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3550         if(!mesh || !channel) {
3551                 meshlink_errno = MESHLINK_EINVAL;
3552                 return;
3553         }
3554
3555         pthread_mutex_lock(&mesh->mutex);
3556         utcp_shutdown(channel->c, direction);
3557         pthread_mutex_unlock(&mesh->mutex);
3558 }
3559
3560 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3561         if(!mesh || !channel) {
3562                 meshlink_errno = MESHLINK_EINVAL;
3563                 return;
3564         }
3565
3566         pthread_mutex_lock(&mesh->mutex);
3567
3568         utcp_close(channel->c);
3569
3570         /* Clean up any outstanding AIO buffers. */
3571         for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3572                 next = aio->next;
3573                 aio_signal(mesh, channel, aio);
3574                 free(aio);
3575         }
3576
3577         for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3578                 next = aio->next;
3579                 aio_signal(mesh, channel, aio);
3580                 free(aio);
3581         }
3582
3583         pthread_mutex_unlock(&mesh->mutex);
3584
3585         free(channel);
3586 }
3587
3588 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3589         if(!mesh || !channel) {
3590                 meshlink_errno = MESHLINK_EINVAL;
3591                 return -1;
3592         }
3593
3594         if(!len) {
3595                 return 0;
3596         }
3597
3598         if(!data) {
3599                 meshlink_errno = MESHLINK_EINVAL;
3600                 return -1;
3601         }
3602
3603         // TODO: more finegrained locking.
3604         // Ideally we want to put the data into the UTCP connection's send buffer.
3605         // Then, preferably only if there is room in the receiver window,
3606         // kick the meshlink thread to go send packets.
3607
3608         ssize_t retval;
3609
3610         pthread_mutex_lock(&mesh->mutex);
3611
3612         /* Disallow direct calls to utcp_send() while we still have AIO active. */
3613         if(channel->aio_send) {
3614                 retval = 0;
3615         } else {
3616                 retval = utcp_send(channel->c, data, len);
3617         }
3618
3619         pthread_mutex_unlock(&mesh->mutex);
3620
3621         if(retval < 0) {
3622                 meshlink_errno = MESHLINK_ENETWORK;
3623         }
3624
3625         return retval;
3626 }
3627
3628 bool meshlink_channel_aio_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len, meshlink_aio_cb_t cb, void *priv) {
3629         if(!mesh || !channel) {
3630                 meshlink_errno = MESHLINK_EINVAL;
3631                 return false;
3632         }
3633
3634         if(!len || !data) {
3635                 meshlink_errno = MESHLINK_EINVAL;
3636                 return false;
3637         }
3638
3639         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3640         aio->data = data;
3641         aio->len = len;
3642         aio->cb.buffer = cb;
3643         aio->priv = priv;
3644
3645         pthread_mutex_lock(&mesh->mutex);
3646
3647         /* Append the AIO buffer descriptor to the end of the chain */
3648         meshlink_aio_buffer_t **p = &channel->aio_send;
3649
3650         while(*p) {
3651                 p = &(*p)->next;
3652         }
3653
3654         *p = aio;
3655
3656         /* Ensure the poll callback is set, and call it right now to push data if possible */
3657         utcp_set_poll_cb(channel->c, channel_poll);
3658         channel_poll(channel->c, len);
3659
3660         pthread_mutex_unlock(&mesh->mutex);
3661
3662         return true;
3663 }
3664
3665 bool meshlink_channel_aio_fd_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, int fd, size_t len, meshlink_aio_fd_cb_t cb, void *priv) {
3666         if(!mesh || !channel) {
3667                 meshlink_errno = MESHLINK_EINVAL;
3668                 return false;
3669         }
3670
3671         if(!len || fd == -1) {
3672                 meshlink_errno = MESHLINK_EINVAL;
3673                 return false;
3674         }
3675
3676         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3677         aio->fd = fd;
3678         aio->len = len;
3679         aio->cb.fd = cb;
3680         aio->priv = priv;
3681
3682         pthread_mutex_lock(&mesh->mutex);
3683
3684         /* Append the AIO buffer descriptor to the end of the chain */
3685         meshlink_aio_buffer_t **p = &channel->aio_send;
3686
3687         while(*p) {
3688                 p = &(*p)->next;
3689         }
3690
3691         *p = aio;
3692
3693         /* Ensure the poll callback is set, and call it right now to push data if possible */
3694         utcp_set_poll_cb(channel->c, channel_poll);
3695         channel_poll(channel->c, len);
3696
3697         pthread_mutex_unlock(&mesh->mutex);
3698
3699         return true;
3700 }
3701
3702 bool meshlink_channel_aio_receive(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len, meshlink_aio_cb_t cb, void *priv) {
3703         if(!mesh || !channel) {
3704                 meshlink_errno = MESHLINK_EINVAL;
3705                 return false;
3706         }
3707
3708         if(!len || !data) {
3709                 meshlink_errno = MESHLINK_EINVAL;
3710                 return false;
3711         }
3712
3713         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3714         aio->data = data;
3715         aio->len = len;
3716         aio->cb.buffer = cb;
3717         aio->priv = priv;
3718
3719         pthread_mutex_lock(&mesh->mutex);
3720
3721         /* Append the AIO buffer descriptor to the end of the chain */
3722         meshlink_aio_buffer_t **p = &channel->aio_receive;
3723
3724         while(*p) {
3725                 p = &(*p)->next;
3726         }
3727
3728         *p = aio;
3729
3730         pthread_mutex_unlock(&mesh->mutex);
3731
3732         return true;
3733 }
3734
3735 bool meshlink_channel_aio_fd_receive(meshlink_handle_t *mesh, meshlink_channel_t *channel, int fd, size_t len, meshlink_aio_fd_cb_t cb, void *priv) {
3736         if(!mesh || !channel) {
3737                 meshlink_errno = MESHLINK_EINVAL;
3738                 return false;
3739         }
3740
3741         if(!len || fd == -1) {
3742                 meshlink_errno = MESHLINK_EINVAL;
3743                 return false;
3744         }
3745
3746         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3747         aio->fd = fd;
3748         aio->len = len;
3749         aio->cb.fd = cb;
3750         aio->priv = priv;
3751
3752         pthread_mutex_lock(&mesh->mutex);
3753
3754         /* Append the AIO buffer descriptor to the end of the chain */
3755         meshlink_aio_buffer_t **p = &channel->aio_receive;
3756
3757         while(*p) {
3758                 p = &(*p)->next;
3759         }
3760
3761         *p = aio;
3762
3763         pthread_mutex_unlock(&mesh->mutex);
3764
3765         return true;
3766 }
3767
3768 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3769         if(!mesh || !channel) {
3770                 meshlink_errno = MESHLINK_EINVAL;
3771                 return -1;
3772         }
3773
3774         return channel->c->flags;
3775 }
3776
3777 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3778         if(!mesh || !channel) {
3779                 meshlink_errno = MESHLINK_EINVAL;
3780                 return -1;
3781         }
3782
3783         return utcp_get_sendq(channel->c);
3784 }
3785
3786 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3787         if(!mesh || !channel) {
3788                 meshlink_errno = MESHLINK_EINVAL;
3789                 return -1;
3790         }
3791
3792         return utcp_get_recvq(channel->c);
3793 }
3794
3795 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3796         if(!mesh || !node) {
3797                 meshlink_errno = MESHLINK_EINVAL;
3798                 return;
3799         }
3800
3801         node_t *n = (node_t *)node;
3802
3803         pthread_mutex_lock(&mesh->mutex);
3804
3805         if(!n->utcp) {
3806                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3807         }
3808
3809         utcp_set_user_timeout(n->utcp, timeout);
3810
3811         pthread_mutex_unlock(&mesh->mutex);
3812 }
3813
3814 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3815         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3816                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3817         }
3818
3819         if(mesh->node_status_cb) {
3820                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3821         }
3822
3823         if(mesh->node_pmtu_cb) {
3824                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3825         }
3826 }
3827
3828 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3829         if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3830                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3831         }
3832 }
3833
3834 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3835         if(!mesh->node_duplicate_cb || n->status.duplicate) {
3836                 return;
3837         }
3838
3839         n->status.duplicate = true;
3840         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3841 }
3842
3843 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3844 #if HAVE_CATTA
3845
3846         if(!mesh) {
3847                 meshlink_errno = MESHLINK_EINVAL;
3848                 return;
3849         }
3850
3851         pthread_mutex_lock(&mesh->mutex);
3852
3853         if(mesh->discovery == enable) {
3854                 goto end;
3855         }
3856
3857         if(mesh->threadstarted) {
3858                 if(enable) {
3859                         discovery_start(mesh);
3860                 } else {
3861                         discovery_stop(mesh);
3862                 }
3863         }
3864
3865         mesh->discovery = enable;
3866
3867 end:
3868         pthread_mutex_unlock(&mesh->mutex);
3869 #else
3870         (void)mesh;
3871         (void)enable;
3872         meshlink_errno = MESHLINK_ENOTSUP;
3873 #endif
3874 }
3875
3876 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3877         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3878                 meshlink_errno = EINVAL;
3879                 return;
3880         }
3881
3882         if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3883                 meshlink_errno = EINVAL;
3884                 return;
3885         }
3886
3887         pthread_mutex_lock(&mesh->mutex);
3888         mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3889         mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3890         pthread_mutex_unlock(&mesh->mutex);
3891 }
3892
3893 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3894         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3895                 meshlink_errno = EINVAL;
3896                 return;
3897         }
3898
3899         if(fast_retry_period < 0) {
3900                 meshlink_errno = EINVAL;
3901                 return;
3902         }
3903
3904         pthread_mutex_lock(&mesh->mutex);
3905         mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3906         pthread_mutex_unlock(&mesh->mutex);
3907 }
3908
3909 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3910         (void)online;
3911
3912         if(!mesh->connections || !mesh->loop.running) {
3913                 return;
3914         }
3915
3916         retry(mesh);
3917 }
3918
3919 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
3920         // We should only call the callback function if we are in the background thread.
3921         if(!mesh->error_cb) {
3922                 return;
3923         }
3924
3925         if(!mesh->threadstarted) {
3926                 return;
3927         }
3928
3929         if(mesh->thread == pthread_self()) {
3930                 mesh->error_cb(mesh, meshlink_errno);
3931         }
3932 }
3933
3934
3935 static void __attribute__((constructor)) meshlink_init(void) {
3936         crypto_init();
3937 }
3938
3939 static void __attribute__((destructor)) meshlink_exit(void) {
3940         crypto_exit();
3941 }