]> git.meshlink.io Git - meshlink-tiny/blob - src/meshlink.c
0d607fe2626997e86d518e4be04df38d08901e09
[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 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
1978         meshlink_packethdr_t *hdr;
1979
1980         if(len > MAXSIZE - sizeof(*hdr)) {
1981                 meshlink_errno = MESHLINK_EINVAL;
1982                 return false;
1983         }
1984
1985         node_t *n = (node_t *)destination;
1986
1987         if(n->status.blacklisted) {
1988                 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1989                 meshlink_errno = MESHLINK_EBLACKLISTED;
1990                 return false;
1991         }
1992
1993         // Prepare the packet
1994         packet->probe = false;
1995         packet->tcp = false;
1996         packet->len = len + sizeof(*hdr);
1997
1998         hdr = (meshlink_packethdr_t *)packet->data;
1999         memset(hdr, 0, sizeof(*hdr));
2000         // leave the last byte as 0 to make sure strings are always
2001         // null-terminated if they are longer than the buffer
2002         strncpy((char *)hdr->destination, destination->name, sizeof(hdr->destination) - 1);
2003         strncpy((char *)hdr->source, mesh->self->name, sizeof(hdr->source) - 1);
2004
2005         memcpy(packet->data + sizeof(*hdr), data, len);
2006
2007         return true;
2008 }
2009
2010 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2011         assert(mesh);
2012         assert(destination);
2013         assert(data);
2014         assert(len);
2015
2016         // Prepare the packet
2017         if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
2018                 return false;
2019         }
2020
2021         // Send it immediately
2022         route(mesh, mesh->self, mesh->packet);
2023
2024         return true;
2025 }
2026
2027 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2028         logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
2029
2030         // Validate arguments
2031         if(!mesh || !destination) {
2032                 meshlink_errno = MESHLINK_EINVAL;
2033                 return false;
2034         }
2035
2036         if(!len) {
2037                 return true;
2038         }
2039
2040         if(!data) {
2041                 meshlink_errno = MESHLINK_EINVAL;
2042                 return false;
2043         }
2044
2045         // Prepare the packet
2046         vpn_packet_t *packet = malloc(sizeof(*packet));
2047
2048         if(!packet) {
2049                 meshlink_errno = MESHLINK_ENOMEM;
2050                 return false;
2051         }
2052
2053         if(!prepare_packet(mesh, destination, data, len, packet)) {
2054                 free(packet);
2055                 return false;
2056         }
2057
2058         // Queue it
2059         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
2060                 free(packet);
2061                 meshlink_errno = MESHLINK_ENOMEM;
2062                 return false;
2063         }
2064
2065         logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
2066
2067         // Notify event loop
2068         signal_trigger(&mesh->loop, &mesh->datafromapp);
2069
2070         return true;
2071 }
2072
2073 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
2074         (void)loop;
2075         meshlink_handle_t *mesh = data;
2076
2077         logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
2078
2079         for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
2080                 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
2081                 mesh->self->in_packets++;
2082                 mesh->self->in_bytes += packet->len;
2083                 route(mesh, mesh->self, packet);
2084                 free(packet);
2085         }
2086 }
2087
2088 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
2089         if(!mesh || !destination) {
2090                 meshlink_errno = MESHLINK_EINVAL;
2091                 return -1;
2092         }
2093
2094         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2095                 abort();
2096         }
2097
2098         node_t *n = (node_t *)destination;
2099
2100         if(!n->status.reachable) {
2101                 pthread_mutex_unlock(&mesh->mutex);
2102                 return 0;
2103
2104         } else if(n->mtuprobes > 30 && n->minmtu) {
2105                 pthread_mutex_unlock(&mesh->mutex);
2106                 return n->minmtu;
2107         } else {
2108                 pthread_mutex_unlock(&mesh->mutex);
2109                 return MTU;
2110         }
2111 }
2112
2113 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
2114         if(!mesh || !node) {
2115                 meshlink_errno = MESHLINK_EINVAL;
2116                 return NULL;
2117         }
2118
2119         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2120                 abort();
2121         }
2122
2123         node_t *n = (node_t *)node;
2124
2125         if(!node_read_public_key(mesh, n) || !n->ecdsa) {
2126                 meshlink_errno = MESHLINK_EINTERNAL;
2127                 pthread_mutex_unlock(&mesh->mutex);
2128                 return false;
2129         }
2130
2131         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
2132
2133         if(!fingerprint) {
2134                 meshlink_errno = MESHLINK_EINTERNAL;
2135         }
2136
2137         pthread_mutex_unlock(&mesh->mutex);
2138         return fingerprint;
2139 }
2140
2141 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
2142         if(!mesh) {
2143                 meshlink_errno = MESHLINK_EINVAL;
2144                 return NULL;
2145         }
2146
2147         return (meshlink_node_t *)mesh->self;
2148 }
2149
2150 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
2151         if(!mesh || !name) {
2152                 meshlink_errno = MESHLINK_EINVAL;
2153                 return NULL;
2154         }
2155
2156         node_t *n = NULL;
2157
2158         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2159                 abort();
2160         }
2161
2162         n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2163         pthread_mutex_unlock(&mesh->mutex);
2164
2165         if(!n) {
2166                 meshlink_errno = MESHLINK_ENOENT;
2167         }
2168
2169         return (meshlink_node_t *)n;
2170 }
2171
2172 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2173         if(!mesh || !name) {
2174                 meshlink_errno = MESHLINK_EINVAL;
2175                 return NULL;
2176         }
2177
2178         meshlink_submesh_t *submesh = NULL;
2179
2180         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2181                 abort();
2182         }
2183
2184         submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2185         pthread_mutex_unlock(&mesh->mutex);
2186
2187         if(!submesh) {
2188                 meshlink_errno = MESHLINK_ENOENT;
2189         }
2190
2191         return submesh;
2192 }
2193
2194 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2195         if(!mesh || !nmemb || (*nmemb && !nodes)) {
2196                 meshlink_errno = MESHLINK_EINVAL;
2197                 return NULL;
2198         }
2199
2200         meshlink_node_t **result;
2201
2202         //lock mesh->nodes
2203         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2204                 abort();
2205         }
2206
2207         *nmemb = mesh->nodes->count;
2208         result = realloc(nodes, *nmemb * sizeof(*nodes));
2209
2210         if(result) {
2211                 meshlink_node_t **p = result;
2212
2213                 for splay_each(node_t, n, mesh->nodes) {
2214                         *p++ = (meshlink_node_t *)n;
2215                 }
2216         } else {
2217                 *nmemb = 0;
2218                 free(nodes);
2219                 meshlink_errno = MESHLINK_ENOMEM;
2220         }
2221
2222         pthread_mutex_unlock(&mesh->mutex);
2223
2224         return result;
2225 }
2226
2227 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) {
2228         meshlink_node_t **result;
2229
2230         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2231                 abort();
2232         }
2233
2234         *nmemb = 0;
2235
2236         for splay_each(node_t, n, mesh->nodes) {
2237                 if(search_node(n, condition)) {
2238                         ++*nmemb;
2239                 }
2240         }
2241
2242         if(*nmemb == 0) {
2243                 free(nodes);
2244                 pthread_mutex_unlock(&mesh->mutex);
2245                 return NULL;
2246         }
2247
2248         result = realloc(nodes, *nmemb * sizeof(*nodes));
2249
2250         if(result) {
2251                 meshlink_node_t **p = result;
2252
2253                 for splay_each(node_t, n, mesh->nodes) {
2254                         if(search_node(n, condition)) {
2255                                 *p++ = (meshlink_node_t *)n;
2256                         }
2257                 }
2258         } else {
2259                 *nmemb = 0;
2260                 free(nodes);
2261                 meshlink_errno = MESHLINK_ENOMEM;
2262         }
2263
2264         pthread_mutex_unlock(&mesh->mutex);
2265
2266         return result;
2267 }
2268
2269 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2270         dev_class_t *devclass = (dev_class_t *)condition;
2271
2272         if(*devclass == (dev_class_t)node->devclass) {
2273                 return true;
2274         }
2275
2276         return false;
2277 }
2278
2279 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2280         if(condition == node->submesh) {
2281                 return true;
2282         }
2283
2284         return false;
2285 }
2286
2287 struct time_range {
2288         time_t start;
2289         time_t end;
2290 };
2291
2292 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2293         const struct time_range *range = condition;
2294         time_t start = node->last_reachable;
2295         time_t end = node->last_unreachable;
2296
2297         if(end < start) {
2298                 end = time(NULL);
2299
2300                 if(end < start) {
2301                         start = end;
2302                 }
2303         }
2304
2305         if(range->end >= range->start) {
2306                 return start <= range->end && end >= range->start;
2307         } else {
2308                 return start > range->start || end < range->end;
2309         }
2310 }
2311
2312 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) {
2313         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2314                 meshlink_errno = MESHLINK_EINVAL;
2315                 return NULL;
2316         }
2317
2318         return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2319 }
2320
2321 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2322         if(!mesh || !submesh || !nmemb) {
2323                 meshlink_errno = MESHLINK_EINVAL;
2324                 return NULL;
2325         }
2326
2327         return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2328 }
2329
2330 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) {
2331         if(!mesh || !nmemb) {
2332                 meshlink_errno = MESHLINK_EINVAL;
2333                 return NULL;
2334         }
2335
2336         struct time_range range = {start, end};
2337
2338         return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2339 }
2340
2341 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2342         if(!mesh || !node) {
2343                 meshlink_errno = MESHLINK_EINVAL;
2344                 return -1;
2345         }
2346
2347         dev_class_t devclass;
2348
2349         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2350                 abort();
2351         }
2352
2353         devclass = ((node_t *)node)->devclass;
2354
2355         pthread_mutex_unlock(&mesh->mutex);
2356
2357         return devclass;
2358 }
2359
2360 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2361         if(!mesh || !node) {
2362                 meshlink_errno = MESHLINK_EINVAL;
2363                 return NULL;
2364         }
2365
2366         node_t *n = (node_t *)node;
2367
2368         meshlink_submesh_t *s;
2369
2370         s = (meshlink_submesh_t *)n->submesh;
2371
2372         return s;
2373 }
2374
2375 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2376         if(!mesh || !node) {
2377                 meshlink_errno = MESHLINK_EINVAL;
2378                 return NULL;
2379         }
2380
2381         node_t *n = (node_t *)node;
2382         bool reachable;
2383
2384         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2385                 abort();
2386         }
2387
2388         reachable = n->status.reachable && !n->status.blacklisted;
2389
2390         if(last_reachable) {
2391                 *last_reachable = n->last_reachable;
2392         }
2393
2394         if(last_unreachable) {
2395                 *last_unreachable = n->last_unreachable;
2396         }
2397
2398         pthread_mutex_unlock(&mesh->mutex);
2399
2400         return reachable;
2401 }
2402
2403 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2404         logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
2405
2406         if(!mesh || !data || !len || !signature || !siglen) {
2407                 meshlink_errno = MESHLINK_EINVAL;
2408                 return false;
2409         }
2410
2411         if(*siglen < MESHLINK_SIGLEN) {
2412                 meshlink_errno = MESHLINK_EINVAL;
2413                 return false;
2414         }
2415
2416         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2417                 abort();
2418         }
2419
2420         if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2421                 meshlink_errno = MESHLINK_EINTERNAL;
2422                 pthread_mutex_unlock(&mesh->mutex);
2423                 return false;
2424         }
2425
2426         *siglen = MESHLINK_SIGLEN;
2427         pthread_mutex_unlock(&mesh->mutex);
2428         return true;
2429 }
2430
2431 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2432         logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
2433
2434         if(!mesh || !source || !data || !len || !signature) {
2435                 meshlink_errno = MESHLINK_EINVAL;
2436                 return false;
2437         }
2438
2439         if(siglen != MESHLINK_SIGLEN) {
2440                 meshlink_errno = MESHLINK_EINVAL;
2441                 return false;
2442         }
2443
2444         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2445                 abort();
2446         }
2447
2448         bool rval = false;
2449
2450         struct node_t *n = (struct node_t *)source;
2451
2452         if(!node_read_public_key(mesh, n)) {
2453                 meshlink_errno = MESHLINK_EINTERNAL;
2454                 rval = false;
2455         } else {
2456                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2457         }
2458
2459         pthread_mutex_unlock(&mesh->mutex);
2460         return rval;
2461 }
2462
2463 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2464         logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
2465
2466         if(!mesh || !node || !address) {
2467                 meshlink_errno = MESHLINK_EINVAL;
2468                 return false;
2469         }
2470
2471         if(!is_valid_hostname(address)) {
2472                 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
2473                 meshlink_errno = MESHLINK_EINVAL;
2474                 return false;
2475         }
2476
2477         if((node_t *)node != mesh->self && !port) {
2478                 logger(mesh, MESHLINK_ERROR, "Missing port number!");
2479                 meshlink_errno = MESHLINK_EINVAL;
2480                 return false;
2481
2482         }
2483
2484         if(port && !is_valid_port(port)) {
2485                 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
2486                 meshlink_errno = MESHLINK_EINVAL;
2487                 return false;
2488         }
2489
2490         char *canonical_address;
2491
2492         xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
2493
2494         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2495                 abort();
2496         }
2497
2498         node_t *n = (node_t *)node;
2499         free(n->canonical_address);
2500         n->canonical_address = canonical_address;
2501
2502         if(!node_write_config(mesh, n, false)) {
2503                 pthread_mutex_unlock(&mesh->mutex);
2504                 return false;
2505         }
2506
2507         pthread_mutex_unlock(&mesh->mutex);
2508
2509         return config_sync(mesh, "current");
2510 }
2511
2512 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
2513         logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
2514
2515         if(!mesh || !node) {
2516                 meshlink_errno = MESHLINK_EINVAL;
2517                 return false;
2518         }
2519
2520         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2521                 abort();
2522         }
2523
2524         node_t *n = (node_t *)node;
2525         free(n->canonical_address);
2526         n->canonical_address = NULL;
2527
2528         if(!node_write_config(mesh, n, false)) {
2529                 pthread_mutex_unlock(&mesh->mutex);
2530                 return false;
2531         }
2532
2533         pthread_mutex_unlock(&mesh->mutex);
2534
2535         return config_sync(mesh, "current");
2536 }
2537
2538 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2539         logger(mesh, MESHLINK_DEBUG, "meshlink_add_address(%s)", address ? address : "(null)");
2540
2541         return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2542 }
2543
2544 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2545         logger(mesh, MESHLINK_DEBUG, "meshlink_add_external_address()");
2546
2547         if(!mesh) {
2548                 meshlink_errno = MESHLINK_EINVAL;
2549                 return false;
2550         }
2551
2552         char *address = meshlink_get_external_address(mesh);
2553
2554         if(!address) {
2555                 return false;
2556         }
2557
2558         bool rval = meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2559         free(address);
2560
2561         return rval;
2562 }
2563
2564 int meshlink_get_port(meshlink_handle_t *mesh) {
2565         if(!mesh) {
2566                 meshlink_errno = MESHLINK_EINVAL;
2567                 return -1;
2568         }
2569
2570         if(!mesh->myport) {
2571                 meshlink_errno = MESHLINK_EINTERNAL;
2572                 return -1;
2573         }
2574
2575         int port;
2576
2577         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2578                 abort();
2579         }
2580
2581         port = atoi(mesh->myport);
2582         pthread_mutex_unlock(&mesh->mutex);
2583
2584         return port;
2585 }
2586
2587 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2588         logger(mesh, MESHLINK_DEBUG, "meshlink_set_port(%d)", port);
2589
2590         if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2591                 meshlink_errno = MESHLINK_EINVAL;
2592                 return false;
2593         }
2594
2595         if(mesh->myport && port == atoi(mesh->myport)) {
2596                 return true;
2597         }
2598
2599         if(!try_bind(mesh, port)) {
2600                 meshlink_errno = MESHLINK_ENETWORK;
2601                 return false;
2602         }
2603
2604         devtool_trybind_probe();
2605
2606         bool rval = false;
2607
2608         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2609                 abort();
2610         }
2611
2612         if(mesh->threadstarted) {
2613                 meshlink_errno = MESHLINK_EINVAL;
2614                 goto done;
2615         }
2616
2617         free(mesh->myport);
2618         xasprintf(&mesh->myport, "%d", port);
2619
2620         /* Close down the network. This also deletes mesh->self. */
2621         close_network_connections(mesh);
2622
2623         /* Recreate mesh->self. */
2624         mesh->self = new_node();
2625         mesh->self->name = xstrdup(mesh->name);
2626         mesh->self->devclass = mesh->devclass;
2627         mesh->self->session_id = mesh->session_id;
2628         xasprintf(&mesh->myport, "%d", port);
2629
2630         if(!node_read_public_key(mesh, mesh->self)) {
2631                 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2632                 meshlink_errno = MESHLINK_ESTORAGE;
2633                 free_node(mesh->self);
2634                 mesh->self = NULL;
2635                 goto done;
2636         } else if(!setup_network(mesh)) {
2637                 meshlink_errno = MESHLINK_ENETWORK;
2638                 goto done;
2639         }
2640
2641         /* Rebuild our own list of recent addresses */
2642         memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2643         add_local_addresses(mesh);
2644
2645         /* Write meshlink.conf with the updated port number */
2646         write_main_config_files(mesh);
2647
2648         rval = config_sync(mesh, "current");
2649
2650 done:
2651         pthread_mutex_unlock(&mesh->mutex);
2652
2653         return rval && meshlink_get_port(mesh) == port;
2654 }
2655
2656 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2657         logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
2658
2659         if(!mesh || !invitation) {
2660                 meshlink_errno = MESHLINK_EINVAL;
2661                 return false;
2662         }
2663
2664         if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
2665                 meshlink_errno = MESHLINK_EINVAL;
2666                 return false;
2667         }
2668
2669         join_state_t state = {
2670                 .mesh = mesh,
2671                 .sock = -1,
2672         };
2673
2674         ecdsa_t *key = NULL;
2675         ecdsa_t *hiskey = NULL;
2676
2677         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2678         char copy[strlen(invitation) + 1];
2679
2680         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2681                 abort();
2682         }
2683
2684         //Before doing meshlink_join make sure we are not connected to another mesh
2685         if(mesh->threadstarted) {
2686                 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2687                 meshlink_errno = MESHLINK_EINVAL;
2688                 goto exit;
2689         }
2690
2691         // 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.
2692         if(mesh->nodes->count > 1) {
2693                 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2694                 meshlink_errno = MESHLINK_EINVAL;
2695                 goto exit;
2696         }
2697
2698         strcpy(copy, invitation);
2699
2700         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2701
2702         char *slash = strchr(copy, '/');
2703
2704         if(!slash) {
2705                 goto invalid;
2706         }
2707
2708         *slash++ = 0;
2709
2710         if(strlen(slash) != 48) {
2711                 goto invalid;
2712         }
2713
2714         char *address = copy;
2715         char *port = NULL;
2716
2717         if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2718                 goto invalid;
2719         }
2720
2721         if(mesh->inviter_commits_first) {
2722                 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
2723         }
2724
2725         // Generate a throw-away key for the invitation.
2726         key = ecdsa_generate();
2727
2728         if(!key) {
2729                 meshlink_errno = MESHLINK_EINTERNAL;
2730                 goto exit;
2731         }
2732
2733         char *b64key = ecdsa_get_base64_public_key(key);
2734         char *comma;
2735
2736         while(address && *address) {
2737                 // We allow commas in the address part to support multiple addresses in one invitation URL.
2738                 comma = strchr(address, ',');
2739
2740                 if(comma) {
2741                         *comma++ = 0;
2742                 }
2743
2744                 // Split of the port
2745                 port = strrchr(address, ':');
2746
2747                 if(!port) {
2748                         goto invalid;
2749                 }
2750
2751                 *port++ = 0;
2752
2753                 // IPv6 address are enclosed in brackets, per RFC 3986
2754                 if(*address == '[') {
2755                         address++;
2756                         char *bracket = strchr(address, ']');
2757
2758                         if(!bracket) {
2759                                 goto invalid;
2760                         }
2761
2762                         *bracket++ = 0;
2763
2764                         if(*bracket) {
2765                                 goto invalid;
2766                         }
2767                 }
2768
2769                 // Connect to the meshlink daemon mentioned in the URL.
2770                 struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(address), xstrdup(port), SOCK_STREAM, 30);
2771
2772                 if(ai) {
2773                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2774                                 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
2775
2776                                 if(state.sock == -1) {
2777                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2778                                         meshlink_errno = MESHLINK_ENETWORK;
2779                                         continue;
2780                                 }
2781
2782 #ifdef SO_NOSIGPIPE
2783                                 int nosigpipe = 1;
2784                                 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
2785 #endif
2786
2787                                 set_timeout(state.sock, 5000);
2788
2789                                 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2790                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2791                                         meshlink_errno = MESHLINK_ENETWORK;
2792                                         closesocket(state.sock);
2793                                         state.sock = -1;
2794                                         continue;
2795                                 }
2796
2797                                 break;
2798                         }
2799
2800                         freeaddrinfo(ai);
2801                 } else {
2802                         meshlink_errno = MESHLINK_ERESOLV;
2803                 }
2804
2805                 if(state.sock != -1 || !comma) {
2806                         break;
2807                 }
2808
2809                 address = comma;
2810         }
2811
2812         if(state.sock == -1) {
2813                 goto exit;
2814         }
2815
2816         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2817
2818         // Tell him we have an invitation, and give him our throw-away key.
2819
2820         state.blen = 0;
2821
2822         if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2823                 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2824                 meshlink_errno = MESHLINK_ENETWORK;
2825                 goto exit;
2826         }
2827
2828         free(b64key);
2829
2830         char hisname[4096] = "";
2831         int code, hismajor, hisminor = 0;
2832
2833         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) {
2834                 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
2835                 meshlink_errno = MESHLINK_ENETWORK;
2836                 goto exit;
2837         }
2838
2839         // Check if the hash of the key he gave us matches the hash in the URL.
2840         char *fingerprint = state.line + 2;
2841         char hishash[64];
2842
2843         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2844                 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
2845                 meshlink_errno = MESHLINK_EINTERNAL;
2846                 goto exit;
2847         }
2848
2849         if(memcmp(hishash, state.hash, 18)) {
2850                 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
2851                 meshlink_errno = MESHLINK_EPEER;
2852                 goto exit;
2853         }
2854
2855         hiskey = ecdsa_set_base64_public_key(fingerprint);
2856
2857         if(!hiskey) {
2858                 meshlink_errno = MESHLINK_EINTERNAL;
2859                 goto exit;
2860         }
2861
2862         // Start an SPTPS session
2863         if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2864                 meshlink_errno = MESHLINK_EINTERNAL;
2865                 goto exit;
2866         }
2867
2868         // Feed rest of input buffer to SPTPS
2869         if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2870                 meshlink_errno = MESHLINK_EPEER;
2871                 goto exit;
2872         }
2873
2874         ssize_t len;
2875         logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2876
2877         while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2878                 if(len < 0) {
2879                         if(errno == EINTR) {
2880                                 continue;
2881                         }
2882
2883                         logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2884                         meshlink_errno = MESHLINK_ENETWORK;
2885                         goto exit;
2886                 }
2887
2888                 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2889                         meshlink_errno = MESHLINK_EPEER;
2890                         goto exit;
2891                 }
2892         }
2893
2894         if(!state.success) {
2895                 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
2896                 meshlink_errno = MESHLINK_EPEER;
2897                 goto exit;
2898         }
2899
2900         sptps_stop(&state.sptps);
2901         ecdsa_free(hiskey);
2902         ecdsa_free(key);
2903         closesocket(state.sock);
2904
2905         pthread_mutex_unlock(&mesh->mutex);
2906         return true;
2907
2908 invalid:
2909         logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
2910         meshlink_errno = MESHLINK_EINVAL;
2911 exit:
2912         sptps_stop(&state.sptps);
2913         ecdsa_free(hiskey);
2914         ecdsa_free(key);
2915
2916         if(state.sock != -1) {
2917                 closesocket(state.sock);
2918         }
2919
2920         pthread_mutex_unlock(&mesh->mutex);
2921         return false;
2922 }
2923
2924 char *meshlink_export(meshlink_handle_t *mesh) {
2925         if(!mesh) {
2926                 meshlink_errno = MESHLINK_EINVAL;
2927                 return NULL;
2928         }
2929
2930         // Create a config file on the fly.
2931
2932         uint8_t buf[4096];
2933         packmsg_output_t out = {buf, sizeof(buf)};
2934         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2935         packmsg_add_str(&out, mesh->name);
2936         packmsg_add_str(&out, CORE_MESH);
2937
2938         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2939                 abort();
2940         }
2941
2942         packmsg_add_int32(&out, mesh->self->devclass);
2943         packmsg_add_bool(&out, mesh->self->status.blacklisted);
2944         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2945
2946         if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
2947                 char *canonical_address = NULL;
2948                 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
2949                 packmsg_add_str(&out, canonical_address);
2950                 free(canonical_address);
2951         } else {
2952                 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2953         }
2954
2955         uint32_t count = 0;
2956
2957         for(uint32_t i = 0; i < MAX_RECENT; i++) {
2958                 if(mesh->self->recent[i].sa.sa_family) {
2959                         count++;
2960                 } else {
2961                         break;
2962                 }
2963         }
2964
2965         packmsg_add_array(&out, count);
2966
2967         for(uint32_t i = 0; i < count; i++) {
2968                 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2969         }
2970
2971         packmsg_add_int64(&out, 0);
2972         packmsg_add_int64(&out, 0);
2973
2974         pthread_mutex_unlock(&mesh->mutex);
2975
2976         if(!packmsg_output_ok(&out)) {
2977                 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2978                 meshlink_errno = MESHLINK_EINTERNAL;
2979                 return NULL;
2980         }
2981
2982         // Prepare a base64-encoded packmsg array containing our config file
2983
2984         uint32_t len = packmsg_output_size(&out, buf);
2985         uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2986         uint8_t *buf2 = xmalloc(len2);
2987         packmsg_output_t out2 = {buf2, len2};
2988         packmsg_add_array(&out2, 1);
2989         packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2990
2991         if(!packmsg_output_ok(&out2)) {
2992                 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2993                 meshlink_errno = MESHLINK_EINTERNAL;
2994                 free(buf2);
2995                 return NULL;
2996         }
2997
2998         b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2999
3000         return (char *)buf2;
3001 }
3002
3003 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
3004         logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
3005
3006         if(!mesh || !data) {
3007                 meshlink_errno = MESHLINK_EINVAL;
3008                 return false;
3009         }
3010
3011         size_t datalen = strlen(data);
3012         uint8_t *buf = xmalloc(datalen);
3013         int buflen = b64decode(data, buf, datalen);
3014
3015         if(!buflen) {
3016                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3017                 free(buf);
3018                 meshlink_errno = MESHLINK_EPEER;
3019                 return false;
3020         }
3021
3022         packmsg_input_t in = {buf, buflen};
3023         uint32_t count = packmsg_get_array(&in);
3024
3025         if(!count) {
3026                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3027                 free(buf);
3028                 meshlink_errno = MESHLINK_EPEER;
3029                 return false;
3030         }
3031
3032         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3033                 abort();
3034         }
3035
3036         while(count--) {
3037                 const void *data2;
3038                 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
3039
3040                 if(!len2) {
3041                         break;
3042                 }
3043
3044                 packmsg_input_t in2 = {data2, len2};
3045                 uint32_t version = packmsg_get_uint32(&in2);
3046                 char *name = packmsg_get_str_dup(&in2);
3047
3048                 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
3049                         free(name);
3050                         packmsg_input_invalidate(&in);
3051                         break;
3052                 }
3053
3054                 if(!check_id(name)) {
3055                         free(name);
3056                         break;
3057                 }
3058
3059                 node_t *n = lookup_node(mesh, name);
3060
3061                 if(n) {
3062                         logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
3063                         free(name);
3064                         continue;
3065                 }
3066
3067                 n = new_node();
3068                 n->name = name;
3069
3070                 config_t config = {data2, len2};
3071
3072                 if(!node_read_from_config(mesh, n, &config)) {
3073                         free_node(n);
3074                         packmsg_input_invalidate(&in);
3075                         break;
3076                 }
3077
3078                 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3079                 n->last_reachable = 0;
3080                 n->last_unreachable = 0;
3081
3082                 if(!node_write_config(mesh, n, true)) {
3083                         free_node(n);
3084                         free(buf);
3085                         return false;
3086                 }
3087
3088                 node_add(mesh, n);
3089         }
3090
3091         pthread_mutex_unlock(&mesh->mutex);
3092
3093         free(buf);
3094
3095         if(!packmsg_done(&in)) {
3096                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3097                 meshlink_errno = MESHLINK_EPEER;
3098                 return false;
3099         }
3100
3101         if(!config_sync(mesh, "current")) {
3102                 return false;
3103         }
3104
3105         return true;
3106 }
3107
3108 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3109         logger(mesh, MESHLINK_DEBUG, "meshlink_forget_node(%s)", node ? node->name : "(null)");
3110
3111         if(!mesh || !node) {
3112                 meshlink_errno = MESHLINK_EINVAL;
3113                 return false;
3114         }
3115
3116         node_t *n = (node_t *)node;
3117
3118         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3119                 abort();
3120         }
3121
3122         /* Check that the node is not reachable */
3123         if(n->status.reachable || n->connection) {
3124                 pthread_mutex_unlock(&mesh->mutex);
3125                 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3126                 return false;
3127         }
3128
3129         /* Check that we don't have any active UTCP connections */
3130         if(n->utcp && utcp_is_active(n->utcp)) {
3131                 pthread_mutex_unlock(&mesh->mutex);
3132                 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3133                 return false;
3134         }
3135
3136         /* Check that we have no active connections to this node */
3137         for list_each(connection_t, c, mesh->connections) {
3138                 if(c->node == n) {
3139                         pthread_mutex_unlock(&mesh->mutex);
3140                         logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3141                         return false;
3142                 }
3143         }
3144
3145         /* Remove any pending outgoings to this node */
3146         if(mesh->outgoings) {
3147                 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3148                         if(outgoing->node == n) {
3149                                 list_delete_node(mesh->outgoings, list_node);
3150                         }
3151                 }
3152         }
3153
3154         /* Delete the config file for this node */
3155         if(!config_delete(mesh, "current", n->name)) {
3156                 pthread_mutex_unlock(&mesh->mutex);
3157                 return false;
3158         }
3159
3160         /* Delete the node struct and any remaining edges referencing this node */
3161         node_del(mesh, n);
3162
3163         pthread_mutex_unlock(&mesh->mutex);
3164
3165         return config_sync(mesh, "current");
3166 }
3167
3168 /* Hint that a hostname may be found at an address
3169  * See header file for detailed comment.
3170  */
3171 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3172         logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
3173
3174         if(!mesh || !node || !addr) {
3175                 meshlink_errno = EINVAL;
3176                 return;
3177         }
3178
3179         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3180                 abort();
3181         }
3182
3183         node_t *n = (node_t *)node;
3184
3185         if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3186                 if(!node_write_config(mesh, n, false)) {
3187                         logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3188                 }
3189         }
3190
3191         pthread_mutex_unlock(&mesh->mutex);
3192         // @TODO do we want to fire off a connection attempt right away?
3193 }
3194
3195 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3196         (void)port;
3197         node_t *n = utcp->priv;
3198         meshlink_handle_t *mesh = n->mesh;
3199
3200         if(mesh->channel_accept_cb && mesh->channel_listen_cb) {
3201                 return mesh->channel_listen_cb(mesh, (meshlink_node_t *)n, port);
3202         } else {
3203                 return mesh->channel_accept_cb;
3204         }
3205 }
3206
3207 /* Finish one AIO buffer, return true if the channel is still open. */
3208 static bool aio_finish_one(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
3209         meshlink_aio_buffer_t *aio = *head;
3210         *head = aio->next;
3211
3212         if(channel->c) {
3213                 channel->in_callback = true;
3214
3215                 if(aio->data) {
3216                         if(aio->cb.buffer) {
3217                                 aio->cb.buffer(mesh, channel, aio->data, aio->done, aio->priv);
3218                         }
3219                 } else {
3220                         if(aio->cb.fd) {
3221                                 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3222                         }
3223                 }
3224
3225                 channel->in_callback = false;
3226
3227                 if(!channel->c) {
3228                         free(aio);
3229                         free(channel);
3230                         return false;
3231                 }
3232         }
3233
3234         free(aio);
3235         return true;
3236 }
3237
3238 /* Finish all AIO buffers, return true if the channel is still open. */
3239 static bool aio_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
3240         while(*head) {
3241                 if(!aio_finish_one(mesh, channel, head)) {
3242                         return false;
3243                 }
3244         }
3245
3246         return true;
3247 }
3248
3249 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3250         meshlink_channel_t *channel = connection->priv;
3251
3252         if(!channel) {
3253                 abort();
3254         }
3255
3256         node_t *n = channel->node;
3257         meshlink_handle_t *mesh = n->mesh;
3258
3259         if(n->status.destroyed) {
3260                 meshlink_channel_close(mesh, channel);
3261                 return len;
3262         }
3263
3264         const char *p = data;
3265         size_t left = len;
3266
3267         while(channel->aio_receive) {
3268                 if(!len) {
3269                         /* This receive callback signalled an error, abort all outstanding AIO buffers. */
3270                         if(!aio_abort(mesh, channel, &channel->aio_receive)) {
3271                                 return len;
3272                         }
3273
3274                         break;
3275                 }
3276
3277                 meshlink_aio_buffer_t *aio = channel->aio_receive;
3278                 size_t todo = aio->len - aio->done;
3279
3280                 if(todo > left) {
3281                         todo = left;
3282                 }
3283
3284                 if(aio->data) {
3285                         memcpy((char *)aio->data + aio->done, p, todo);
3286                 } else {
3287                         ssize_t result = write(aio->fd, p, todo);
3288
3289                         if(result <= 0) {
3290                                 if(result < 0 && errno == EINTR) {
3291                                         continue;
3292                                 }
3293
3294                                 /* Writing to fd failed, cancel just this AIO buffer. */
3295                                 logger(mesh, MESHLINK_ERROR, "Writing to AIO fd %d failed: %s", aio->fd, strerror(errno));
3296
3297                                 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
3298                                         return len;
3299                                 }
3300
3301                                 continue;
3302                         }
3303
3304                         todo = result;
3305                 }
3306
3307                 aio->done += todo;
3308                 p += todo;
3309                 left -= todo;
3310
3311                 if(aio->done == aio->len) {
3312                         if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
3313                                 return len;
3314                         }
3315                 }
3316
3317                 if(!left) {
3318                         return len;
3319                 }
3320         }
3321
3322         if(channel->receive_cb) {
3323                 channel->receive_cb(mesh, channel, p, left);
3324         }
3325
3326         return len;
3327 }
3328
3329 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3330         node_t *n = utcp_connection->utcp->priv;
3331
3332         if(!n) {
3333                 abort();
3334         }
3335
3336         meshlink_handle_t *mesh = n->mesh;
3337
3338         if(!mesh->channel_accept_cb) {
3339                 return;
3340         }
3341
3342         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3343         channel->node = n;
3344         channel->c = utcp_connection;
3345
3346         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3347                 utcp_accept(utcp_connection, channel_recv, channel);
3348         } else {
3349                 free(channel);
3350         }
3351 }
3352
3353 static void channel_retransmit(struct utcp_connection *utcp_connection) {
3354         node_t *n = utcp_connection->utcp->priv;
3355         meshlink_handle_t *mesh = n->mesh;
3356
3357         if(n->mtuprobes == 31 && n->mtutimeout.cb) {
3358                 timeout_set(&mesh->loop, &n->mtutimeout, &(struct timespec) {
3359                         0, 0
3360                 });
3361         }
3362 }
3363
3364 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3365         node_t *n = utcp->priv;
3366
3367         if(n->status.destroyed) {
3368                 return -1;
3369         }
3370
3371         meshlink_handle_t *mesh = n->mesh;
3372         return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3373 }
3374
3375 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3376         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_receive_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
3377
3378         if(!mesh || !channel) {
3379                 meshlink_errno = MESHLINK_EINVAL;
3380                 return;
3381         }
3382
3383         channel->receive_cb = cb;
3384 }
3385
3386 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3387         (void)mesh;
3388         node_t *n = (node_t *)source;
3389
3390         if(!n->utcp) {
3391                 abort();
3392         }
3393
3394         utcp_recv(n->utcp, data, len);
3395 }
3396
3397 static void channel_poll(struct utcp_connection *connection, size_t len) {
3398         meshlink_channel_t *channel = connection->priv;
3399
3400         if(!channel) {
3401                 abort();
3402         }
3403
3404         node_t *n = channel->node;
3405         meshlink_handle_t *mesh = n->mesh;
3406
3407         while(channel->aio_send) {
3408                 if(!len) {
3409                         /* This poll callback signalled an error, abort all outstanding AIO buffers. */
3410                         if(!aio_abort(mesh, channel, &channel->aio_send)) {
3411                                 return;
3412                         }
3413
3414                         break;
3415                 }
3416
3417                 /* We have at least one AIO buffer. Send as much as possible from the buffers. */
3418                 meshlink_aio_buffer_t *aio = channel->aio_send;
3419                 size_t todo = aio->len - aio->done;
3420                 ssize_t sent;
3421
3422                 if(todo > len) {
3423                         todo = len;
3424                 }
3425
3426                 if(aio->data) {
3427                         sent = utcp_send(connection, (char *)aio->data + aio->done, todo);
3428                 } else {
3429                         /* Limit the amount we read at once to avoid stack overflows */
3430                         if(todo > 65536) {
3431                                 todo = 65536;
3432                         }
3433
3434                         char buf[todo];
3435                         ssize_t result = read(aio->fd, buf, todo);
3436
3437                         if(result > 0) {
3438                                 todo = result;
3439                                 sent = utcp_send(connection, buf, todo);
3440                         } else {
3441                                 if(result < 0 && errno == EINTR) {
3442                                         continue;
3443                                 }
3444
3445                                 /* Reading from fd failed, cancel just this AIO buffer. */
3446                                 if(result != 0) {
3447                                         logger(mesh, MESHLINK_ERROR, "Reading from AIO fd %d failed: %s", aio->fd, strerror(errno));
3448                                 }
3449
3450                                 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
3451                                         return;
3452                                 }
3453
3454                                 continue;
3455                         }
3456                 }
3457
3458                 if(sent != (ssize_t)todo) {
3459                         /* Sending failed, abort all outstanding AIO buffers and send a poll callback. */
3460                         if(!aio_abort(mesh, channel, &channel->aio_send)) {
3461                                 return;
3462                         }
3463
3464                         len = 0;
3465                         break;
3466                 }
3467
3468                 aio->done += sent;
3469                 len -= sent;
3470
3471                 /* If we didn't finish this buffer, exit early. */
3472                 if(aio->done < aio->len) {
3473                         return;
3474                 }
3475
3476                 /* Signal completion of this buffer, and go to the next one. */
3477                 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
3478                         return;
3479                 }
3480
3481                 if(!len) {
3482                         return;
3483                 }
3484         }
3485
3486         if(channel->poll_cb) {
3487                 channel->poll_cb(mesh, channel, len);
3488         } else {
3489                 utcp_set_poll_cb(connection, NULL);
3490         }
3491 }
3492
3493 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3494         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_poll_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
3495
3496         if(!mesh || !channel) {
3497                 meshlink_errno = MESHLINK_EINVAL;
3498                 return;
3499         }
3500
3501         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3502                 abort();
3503         }
3504
3505         channel->poll_cb = cb;
3506         utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3507         pthread_mutex_unlock(&mesh->mutex);
3508 }
3509
3510 void meshlink_set_channel_listen_cb(meshlink_handle_t *mesh, meshlink_channel_listen_cb_t cb) {
3511         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_listen_cb(%p)", (void *)(intptr_t)cb);
3512
3513         if(!mesh) {
3514                 meshlink_errno = MESHLINK_EINVAL;
3515                 return;
3516         }
3517
3518         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3519                 abort();
3520         }
3521
3522         mesh->channel_listen_cb = cb;
3523
3524         pthread_mutex_unlock(&mesh->mutex);
3525 }
3526
3527 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3528         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_accept_cb(%p)", (void *)(intptr_t)cb);
3529
3530         if(!mesh) {
3531                 meshlink_errno = MESHLINK_EINVAL;
3532                 return;
3533         }
3534
3535         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3536                 abort();
3537         }
3538
3539         mesh->channel_accept_cb = cb;
3540         mesh->receive_cb = channel_receive;
3541
3542         for splay_each(node_t, n, mesh->nodes) {
3543                 if(!n->utcp && n != mesh->self) {
3544                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3545                         utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3546                         utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3547                 }
3548         }
3549
3550         pthread_mutex_unlock(&mesh->mutex);
3551 }
3552
3553 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3554         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf(%p, %zu)", (void *)channel, size);
3555
3556         meshlink_set_channel_sndbuf_storage(mesh, channel, NULL, size);
3557 }
3558
3559 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3560         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf(%p, %zu)", (void *)channel, size);
3561
3562         meshlink_set_channel_rcvbuf_storage(mesh, channel, NULL, size);
3563 }
3564
3565 void meshlink_set_channel_sndbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
3566         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
3567
3568         if(!mesh || !channel) {
3569                 meshlink_errno = MESHLINK_EINVAL;
3570                 return;
3571         }
3572
3573         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3574                 abort();
3575         }
3576
3577         utcp_set_sndbuf(channel->c, buf, size);
3578         pthread_mutex_unlock(&mesh->mutex);
3579 }
3580
3581 void meshlink_set_channel_rcvbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
3582         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
3583
3584         if(!mesh || !channel) {
3585                 meshlink_errno = MESHLINK_EINVAL;
3586                 return;
3587         }
3588
3589         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3590                 abort();
3591         }
3592
3593         utcp_set_rcvbuf(channel->c, buf, size);
3594         pthread_mutex_unlock(&mesh->mutex);
3595 }
3596
3597 void meshlink_set_channel_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint32_t flags) {
3598         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_flags(%p, %u)", (void *)channel, flags);
3599
3600         if(!mesh || !channel) {
3601                 meshlink_errno = MESHLINK_EINVAL;
3602                 return;
3603         }
3604
3605         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3606                 abort();
3607         }
3608
3609         utcp_set_flags(channel->c, flags);
3610         pthread_mutex_unlock(&mesh->mutex);
3611 }
3612
3613 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) {
3614         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);
3615
3616         if(data && len) {
3617                 abort();        // TODO: handle non-NULL data
3618         }
3619
3620         if(!mesh || !node) {
3621                 meshlink_errno = MESHLINK_EINVAL;
3622                 return NULL;
3623         }
3624
3625         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3626                 abort();
3627         }
3628
3629         node_t *n = (node_t *)node;
3630
3631         if(!n->utcp) {
3632                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3633                 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3634                 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3635                 mesh->receive_cb = channel_receive;
3636
3637                 if(!n->utcp) {
3638                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3639                         pthread_mutex_unlock(&mesh->mutex);
3640                         return NULL;
3641                 }
3642         }
3643
3644         if(n->status.blacklisted) {
3645                 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3646                 meshlink_errno = MESHLINK_EBLACKLISTED;
3647                 pthread_mutex_unlock(&mesh->mutex);
3648                 return NULL;
3649         }
3650
3651         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3652         channel->node = n;
3653         channel->receive_cb = cb;
3654
3655         if(data && !len) {
3656                 channel->priv = (void *)data;
3657         }
3658
3659         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3660
3661         pthread_mutex_unlock(&mesh->mutex);
3662
3663         if(!channel->c) {
3664                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3665                 free(channel);
3666                 return NULL;
3667         }
3668
3669         return channel;
3670 }
3671
3672 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) {
3673         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len);
3674
3675         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3676 }
3677
3678 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3679         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_shutdown(%p, %d)", (void *)channel, direction);
3680
3681         if(!mesh || !channel) {
3682                 meshlink_errno = MESHLINK_EINVAL;
3683                 return;
3684         }
3685
3686         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3687                 abort();
3688         }
3689
3690         utcp_shutdown(channel->c, direction);
3691         pthread_mutex_unlock(&mesh->mutex);
3692 }
3693
3694 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3695         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_close(%p)", (void *)channel);
3696
3697         if(!mesh || !channel) {
3698                 meshlink_errno = MESHLINK_EINVAL;
3699                 return;
3700         }
3701
3702         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3703                 abort();
3704         }
3705
3706         if(channel->c) {
3707                 utcp_close(channel->c);
3708                 channel->c = NULL;
3709
3710                 /* Clean up any outstanding AIO buffers. */
3711                 aio_abort(mesh, channel, &channel->aio_send);
3712                 aio_abort(mesh, channel, &channel->aio_receive);
3713         }
3714
3715         if(!channel->in_callback) {
3716                 free(channel);
3717         }
3718
3719         pthread_mutex_unlock(&mesh->mutex);
3720 }
3721
3722 void meshlink_channel_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3723         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_abort(%p)", (void *)channel);
3724
3725         if(!mesh || !channel) {
3726                 meshlink_errno = MESHLINK_EINVAL;
3727                 return;
3728         }
3729
3730         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3731                 abort();
3732         }
3733
3734         if(channel->c) {
3735                 utcp_abort(channel->c);
3736                 channel->c = NULL;
3737
3738                 /* Clean up any outstanding AIO buffers. */
3739                 aio_abort(mesh, channel, &channel->aio_send);
3740                 aio_abort(mesh, channel, &channel->aio_receive);
3741         }
3742
3743         if(!channel->in_callback) {
3744                 free(channel);
3745         }
3746
3747         pthread_mutex_unlock(&mesh->mutex);
3748 }
3749
3750 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3751         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_send(%p, %p, %zu)", (void *)channel, data, len);
3752
3753         if(!mesh || !channel) {
3754                 meshlink_errno = MESHLINK_EINVAL;
3755                 return -1;
3756         }
3757
3758         if(!len) {
3759                 return 0;
3760         }
3761
3762         if(!data) {
3763                 meshlink_errno = MESHLINK_EINVAL;
3764                 return -1;
3765         }
3766
3767         // TODO: more finegrained locking.
3768         // Ideally we want to put the data into the UTCP connection's send buffer.
3769         // Then, preferably only if there is room in the receiver window,
3770         // kick the meshlink thread to go send packets.
3771
3772         ssize_t retval;
3773
3774         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3775                 abort();
3776         }
3777
3778         /* Disallow direct calls to utcp_send() while we still have AIO active. */
3779         if(channel->aio_send) {
3780                 retval = 0;
3781         } else {
3782                 retval = utcp_send(channel->c, data, len);
3783         }
3784
3785         pthread_mutex_unlock(&mesh->mutex);
3786
3787         if(retval < 0) {
3788                 meshlink_errno = MESHLINK_ENETWORK;
3789         }
3790
3791         return retval;
3792 }
3793
3794 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) {
3795         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_send(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
3796
3797         if(!mesh || !channel) {
3798                 meshlink_errno = MESHLINK_EINVAL;
3799                 return false;
3800         }
3801
3802         if(!len || !data) {
3803                 meshlink_errno = MESHLINK_EINVAL;
3804                 return false;
3805         }
3806
3807         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3808         aio->data = data;
3809         aio->len = len;
3810         aio->cb.buffer = cb;
3811         aio->priv = priv;
3812
3813         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3814                 abort();
3815         }
3816
3817         /* Append the AIO buffer descriptor to the end of the chain */
3818         meshlink_aio_buffer_t **p = &channel->aio_send;
3819
3820         while(*p) {
3821                 p = &(*p)->next;
3822         }
3823
3824         *p = aio;
3825
3826         /* Ensure the poll callback is set, and call it right now to push data if possible */
3827         utcp_set_poll_cb(channel->c, channel_poll);
3828         size_t todo = MIN(len, utcp_get_rcvbuf_free(channel->c));
3829
3830         if(todo) {
3831                 channel_poll(channel->c, todo);
3832         }
3833
3834         pthread_mutex_unlock(&mesh->mutex);
3835
3836         return true;
3837 }
3838
3839 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) {
3840         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_send(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
3841
3842         if(!mesh || !channel) {
3843                 meshlink_errno = MESHLINK_EINVAL;
3844                 return false;
3845         }
3846
3847         if(!len || fd == -1) {
3848                 meshlink_errno = MESHLINK_EINVAL;
3849                 return false;
3850         }
3851
3852         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3853         aio->fd = fd;
3854         aio->len = len;
3855         aio->cb.fd = cb;
3856         aio->priv = priv;
3857
3858         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3859                 abort();
3860         }
3861
3862         /* Append the AIO buffer descriptor to the end of the chain */
3863         meshlink_aio_buffer_t **p = &channel->aio_send;
3864
3865         while(*p) {
3866                 p = &(*p)->next;
3867         }
3868
3869         *p = aio;
3870
3871         /* Ensure the poll callback is set, and call it right now to push data if possible */
3872         utcp_set_poll_cb(channel->c, channel_poll);
3873         size_t left = utcp_get_rcvbuf_free(channel->c);
3874
3875         if(left) {
3876                 channel_poll(channel->c, left);
3877         }
3878
3879         pthread_mutex_unlock(&mesh->mutex);
3880
3881         return true;
3882 }
3883
3884 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) {
3885         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_receive(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
3886
3887         if(!mesh || !channel) {
3888                 meshlink_errno = MESHLINK_EINVAL;
3889                 return false;
3890         }
3891
3892         if(!len || !data) {
3893                 meshlink_errno = MESHLINK_EINVAL;
3894                 return false;
3895         }
3896
3897         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3898         aio->data = data;
3899         aio->len = len;
3900         aio->cb.buffer = cb;
3901         aio->priv = priv;
3902
3903         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3904                 abort();
3905         }
3906
3907         /* Append the AIO buffer descriptor to the end of the chain */
3908         meshlink_aio_buffer_t **p = &channel->aio_receive;
3909
3910         while(*p) {
3911                 p = &(*p)->next;
3912         }
3913
3914         *p = aio;
3915
3916         pthread_mutex_unlock(&mesh->mutex);
3917
3918         return true;
3919 }
3920
3921 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) {
3922         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_receive(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
3923
3924         if(!mesh || !channel) {
3925                 meshlink_errno = MESHLINK_EINVAL;
3926                 return false;
3927         }
3928
3929         if(!len || fd == -1) {
3930                 meshlink_errno = MESHLINK_EINVAL;
3931                 return false;
3932         }
3933
3934         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3935         aio->fd = fd;
3936         aio->len = len;
3937         aio->cb.fd = cb;
3938         aio->priv = priv;
3939
3940         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3941                 abort();
3942         }
3943
3944         /* Append the AIO buffer descriptor to the end of the chain */
3945         meshlink_aio_buffer_t **p = &channel->aio_receive;
3946
3947         while(*p) {
3948                 p = &(*p)->next;
3949         }
3950
3951         *p = aio;
3952
3953         pthread_mutex_unlock(&mesh->mutex);
3954
3955         return true;
3956 }
3957
3958 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3959         if(!mesh || !channel) {
3960                 meshlink_errno = MESHLINK_EINVAL;
3961                 return -1;
3962         }
3963
3964         return channel->c->flags;
3965 }
3966
3967 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3968         if(!mesh || !channel) {
3969                 meshlink_errno = MESHLINK_EINVAL;
3970                 return -1;
3971         }
3972
3973         return utcp_get_sendq(channel->c);
3974 }
3975
3976 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3977         if(!mesh || !channel) {
3978                 meshlink_errno = MESHLINK_EINVAL;
3979                 return -1;
3980         }
3981
3982         return utcp_get_recvq(channel->c);
3983 }
3984
3985 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3986         if(!mesh || !channel) {
3987                 meshlink_errno = MESHLINK_EINVAL;
3988                 return -1;
3989         }
3990
3991         return utcp_get_mss(channel->node->utcp);
3992 }
3993
3994 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3995         logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_channel_timeout(%s, %d)", node ? node->name : "(null)", timeout);
3996
3997         if(!mesh || !node) {
3998                 meshlink_errno = MESHLINK_EINVAL;
3999                 return;
4000         }
4001
4002         node_t *n = (node_t *)node;
4003
4004         if(pthread_mutex_lock(&mesh->mutex) != 0) {
4005                 abort();
4006         }
4007
4008         if(!n->utcp) {
4009                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4010                 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4011                 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4012         }
4013
4014         utcp_set_user_timeout(n->utcp, timeout);
4015
4016         pthread_mutex_unlock(&mesh->mutex);
4017 }
4018
4019 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
4020         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
4021                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4022                 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4023                 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4024         }
4025
4026         if(mesh->node_status_cb) {
4027                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
4028         }
4029
4030         if(mesh->node_pmtu_cb) {
4031                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4032         }
4033 }
4034
4035 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
4036         utcp_set_mtu(n->utcp, (n->minmtu > MINMTU ? n->minmtu : MINMTU) - sizeof(meshlink_packethdr_t));
4037
4038         if(mesh->node_pmtu_cb && !n->status.blacklisted) {
4039                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4040         }
4041 }
4042
4043 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
4044         if(!mesh->node_duplicate_cb || n->status.duplicate) {
4045                 return;
4046         }
4047
4048         n->status.duplicate = true;
4049         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
4050 }
4051
4052 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
4053         logger(mesh, MESHLINK_DEBUG, "meshlink_enable_discovery(%d)", enable);
4054
4055         if(!mesh) {
4056                 meshlink_errno = MESHLINK_EINVAL;
4057                 return;
4058         }
4059
4060         if(pthread_mutex_lock(&mesh->mutex) != 0) {
4061                 abort();
4062         }
4063
4064         if(mesh->discovery.enabled == enable) {
4065                 goto end;
4066         }
4067
4068         if(mesh->threadstarted) {
4069                 if(enable) {
4070                         discovery_start(mesh);
4071                 } else {
4072                         discovery_stop(mesh);
4073                 }
4074         }
4075
4076         mesh->discovery.enabled = enable;
4077
4078 end:
4079         pthread_mutex_unlock(&mesh->mutex);
4080 }
4081
4082 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
4083         logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
4084
4085         if(!mesh) {
4086                 meshlink_errno = MESHLINK_EINVAL;
4087                 return;
4088         }
4089
4090         if(pthread_mutex_lock(&mesh->mutex) != 0) {
4091                 abort();
4092         }
4093
4094         if(mesh->discovery.enabled) {
4095                 scan_ifaddrs(mesh);
4096         }
4097
4098         if(mesh->loop.now.tv_sec > mesh->discovery.last_update + 5) {
4099                 mesh->discovery.last_update = mesh->loop.now.tv_sec;
4100                 handle_network_change(mesh, 1);
4101         }
4102
4103         pthread_mutex_unlock(&mesh->mutex);
4104 }
4105
4106 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
4107         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
4108
4109         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4110                 meshlink_errno = EINVAL;
4111                 return;
4112         }
4113
4114         if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
4115                 meshlink_errno = EINVAL;
4116                 return;
4117         }
4118
4119         if(pthread_mutex_lock(&mesh->mutex) != 0) {
4120                 abort();
4121         }
4122
4123         mesh->dev_class_traits[devclass].pinginterval = pinginterval;
4124         mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
4125         pthread_mutex_unlock(&mesh->mutex);
4126 }
4127
4128 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
4129         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
4130
4131         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4132                 meshlink_errno = EINVAL;
4133                 return;
4134         }
4135
4136         if(fast_retry_period < 0) {
4137                 meshlink_errno = EINVAL;
4138                 return;
4139         }
4140
4141         if(pthread_mutex_lock(&mesh->mutex) != 0) {
4142                 abort();
4143         }
4144
4145         mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
4146         pthread_mutex_unlock(&mesh->mutex);
4147 }
4148
4149 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
4150         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
4151
4152         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4153                 meshlink_errno = EINVAL;
4154                 return;
4155         }
4156
4157         if(maxtimeout < 0) {
4158                 meshlink_errno = EINVAL;
4159                 return;
4160         }
4161
4162         if(pthread_mutex_lock(&mesh->mutex) != 0) {
4163                 abort();
4164         }
4165
4166         mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
4167         pthread_mutex_unlock(&mesh->mutex);
4168 }
4169
4170 void meshlink_reset_timers(struct meshlink_handle *mesh) {
4171         logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
4172
4173         if(!mesh) {
4174                 return;
4175         }
4176
4177         if(pthread_mutex_lock(&mesh->mutex) != 0) {
4178                 abort();
4179         }
4180
4181         handle_network_change(mesh, true);
4182
4183         if(mesh->discovery.enabled) {
4184                 discovery_refresh(mesh);
4185         }
4186
4187         pthread_mutex_unlock(&mesh->mutex);
4188 }
4189
4190 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
4191         logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
4192
4193         if(!mesh) {
4194                 meshlink_errno = EINVAL;
4195                 return;
4196         }
4197
4198         if(pthread_mutex_lock(&mesh->mutex) != 0) {
4199                 abort();
4200         }
4201
4202         mesh->inviter_commits_first = inviter_commits_first;
4203         pthread_mutex_unlock(&mesh->mutex);
4204 }
4205
4206 void meshlink_set_external_address_discovery_url(struct meshlink_handle *mesh, const char *url) {
4207         logger(mesh, MESHLINK_DEBUG, "meshlink_set_external_address_discovery_url(%s)", url ? url : "(null)");
4208
4209         if(!mesh) {
4210                 meshlink_errno = EINVAL;
4211                 return;
4212         }
4213
4214         if(url && (strncmp(url, "http://", 7) || strchr(url, ' '))) {
4215                 meshlink_errno = EINVAL;
4216                 return;
4217         }
4218
4219         if(pthread_mutex_lock(&mesh->mutex) != 0) {
4220                 abort();
4221         }
4222
4223         free(mesh->external_address_url);
4224         mesh->external_address_url = url ? xstrdup(url) : NULL;
4225         pthread_mutex_unlock(&mesh->mutex);
4226 }
4227
4228 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
4229         logger(mesh, MESHLINK_DEBUG, "meshlink_set_scheduling_granularity(%ld)", granularity);
4230
4231         if(!mesh || granularity < 0) {
4232                 meshlink_errno = EINVAL;
4233                 return;
4234         }
4235
4236         utcp_set_clock_granularity(granularity);
4237 }
4238
4239 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
4240         logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
4241
4242         if(!mesh) {
4243                 meshlink_errno = EINVAL;
4244                 return;
4245         }
4246
4247         if(pthread_mutex_lock(&mesh->mutex) != 0) {
4248                 abort();
4249         }
4250
4251         mesh->storage_policy = policy;
4252         pthread_mutex_unlock(&mesh->mutex);
4253 }
4254
4255 void handle_network_change(meshlink_handle_t *mesh, bool online) {
4256         (void)online;
4257
4258         if(!mesh->connections || !mesh->loop.running) {
4259                 return;
4260         }
4261
4262         retry(mesh);
4263         signal_trigger(&mesh->loop, &mesh->datafromapp);
4264 }
4265
4266 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
4267         // We should only call the callback function if we are in the background thread.
4268         if(!mesh->error_cb) {
4269                 return;
4270         }
4271
4272         if(!mesh->threadstarted) {
4273                 return;
4274         }
4275
4276         if(mesh->thread == pthread_self()) {
4277                 mesh->error_cb(mesh, cb_errno);
4278         }
4279 }
4280
4281 static void __attribute__((constructor)) meshlink_init(void) {
4282         crypto_init();
4283         utcp_set_clock_granularity(10000);
4284 }
4285
4286 static void __attribute__((destructor)) meshlink_exit(void) {
4287         crypto_exit();
4288 }