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