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