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