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