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