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