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