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