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