]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Don't call abort() when no channel receive callback is set.
[meshlink] / src / meshlink.c
1 /*
2     meshlink.c -- Implementation of the MeshLink API.
3     Copyright (C) 2014, 2017 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 #define VAR_SERVER 1    /* Should be in meshlink.conf */
20 #define VAR_HOST 2      /* Can be in host config file */
21 #define VAR_MULTIPLE 4  /* Multiple statements allowed */
22 #define VAR_OBSOLETE 8  /* Should not be used anymore */
23 #define VAR_SAFE 16     /* Variable is safe when accepting invitations */
24 #define MAX_ADDRESS_LENGTH 45 /* Max length of an (IPv6) address */
25 #define MAX_PORT_LENGTH 5 /* 0-65535 */
26 typedef struct {
27         const char *name;
28         int type;
29 } var_t;
30
31 #include "system.h"
32 #include <pthread.h>
33
34 #include "crypto.h"
35 #include "ecdsagen.h"
36 #include "logger.h"
37 #include "meshlink_internal.h"
38 #include "netutl.h"
39 #include "node.h"
40 #include "protocol.h"
41 #include "route.h"
42 #include "sockaddr.h"
43 #include "utils.h"
44 #include "xalloc.h"
45 #include "ed25519/sha512.h"
46 #include "discovery.h"
47
48 #ifndef MSG_NOSIGNAL
49 #define MSG_NOSIGNAL 0
50 #endif
51
52 __thread meshlink_errno_t meshlink_errno;
53 meshlink_log_cb_t global_log_cb;
54 meshlink_log_level_t global_log_level;
55
56 //TODO: this can go away completely
57 const var_t variables[] = {
58         /* Server configuration */
59         {"AddressFamily", VAR_SERVER},
60         {"AutoConnect", VAR_SERVER | VAR_SAFE},
61         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
62         {"BindToInterface", VAR_SERVER},
63         {"Broadcast", VAR_SERVER | VAR_SAFE},
64         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
65         {"DecrementTTL", VAR_SERVER},
66         {"Device", VAR_SERVER},
67         {"DeviceType", VAR_SERVER},
68         {"DirectOnly", VAR_SERVER},
69         {"ECDSAPrivateKeyFile", VAR_SERVER},
70         {"ExperimentalProtocol", VAR_SERVER},
71         {"Forwarding", VAR_SERVER},
72         {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
73         {"Hostnames", VAR_SERVER},
74         {"IffOneQueue", VAR_SERVER},
75         {"Interface", VAR_SERVER},
76         {"KeyExpire", VAR_SERVER},
77         {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
78         {"LocalDiscovery", VAR_SERVER},
79         {"MACExpire", VAR_SERVER},
80         {"MaxConnectionBurst", VAR_SERVER},
81         {"MaxOutputBufferSize", VAR_SERVER},
82         {"MaxTimeout", VAR_SERVER},
83         {"Mode", VAR_SERVER | VAR_SAFE},
84         {"Name", VAR_SERVER},
85         {"PingInterval", VAR_SERVER},
86         {"PingTimeout", VAR_SERVER},
87         {"PriorityInheritance", VAR_SERVER},
88         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
89         {"PrivateKeyFile", VAR_SERVER},
90         {"ProcessPriority", VAR_SERVER},
91         {"Proxy", VAR_SERVER},
92         {"ReplayWindow", VAR_SERVER},
93         {"ScriptsExtension", VAR_SERVER},
94         {"ScriptsInterpreter", VAR_SERVER},
95         {"StrictSubnets", VAR_SERVER},
96         {"TunnelServer", VAR_SERVER},
97         {"VDEGroup", VAR_SERVER},
98         {"VDEPort", VAR_SERVER},
99         /* Host configuration */
100         {"Address", VAR_HOST | VAR_MULTIPLE},
101         {"Cipher", VAR_SERVER | VAR_HOST},
102         {"ClampMSS", VAR_SERVER | VAR_HOST},
103         {"Compression", VAR_SERVER | VAR_HOST},
104         {"Digest", VAR_SERVER | VAR_HOST},
105         {"ECDSAPublicKey", VAR_HOST},
106         {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
107         {"IndirectData", VAR_SERVER | VAR_HOST},
108         {"MACLength", VAR_SERVER | VAR_HOST},
109         {"PMTU", VAR_SERVER | VAR_HOST},
110         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
111         {"Port", VAR_HOST},
112         {"PublicKey", VAR_HOST | VAR_OBSOLETE},
113         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
114         {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
115         {"TCPOnly", VAR_SERVER | VAR_HOST},
116         {"Weight", VAR_HOST | VAR_SAFE},
117         {NULL, 0}
118 };
119
120 static bool fcopy(FILE *out, const char *filename) {
121         FILE *in = fopen(filename, "r");
122         if(!in) {
123                 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
124                 return false;
125         }
126
127         char buf[1024];
128         size_t len;
129         while((len = fread(buf, 1, sizeof buf, in)))
130                 fwrite(buf, len, 1, out);
131         fclose(in);
132         return true;
133 }
134
135 static int rstrip(char *value) {
136         int len = strlen(value);
137         while(len && strchr("\t\r\n ", value[len - 1]))
138                 value[--len] = 0;
139         return len;
140 }
141
142 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
143         char line[4096];
144         if(!filename || (*hostname && *port))
145                 return;
146
147         FILE *f = fopen(filename, "r");
148         if(!f)
149                 return;
150
151         while(fgets(line, sizeof line, f)) {
152                 if(!rstrip(line))
153                         continue;
154                 char *p = line, *q;
155                 p += strcspn(p, "\t =");
156                 if(!*p)
157                         continue;
158                 q = p + strspn(p, "\t ");
159                 if(*q == '=')
160                         q += 1 + strspn(q + 1, "\t ");
161                 *p = 0;
162                 p = q + strcspn(q, "\t ");
163                 if(*p)
164                         *p++ = 0;
165                 p += strspn(p, "\t ");
166                 p[strcspn(p, "\t ")] = 0;
167
168                 if(!*port && !strcasecmp(line, "Port")) {
169                         *port = xstrdup(q);
170                 } else if(!*hostname && !strcasecmp(line, "Address")) {
171                         *hostname = xstrdup(q);
172                         if(*p) {
173                                 free(*port);
174                                 *port = xstrdup(p);
175                         }
176                 }
177
178                 if(*hostname && *port)
179                         break;
180         }
181
182         fclose(f);
183 }
184
185 static bool is_valid_hostname(const char *hostname) {
186         for(const char *p = hostname; *p; p++) {
187                 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':'))
188                         return false;
189         }
190
191         return true;
192 }
193
194 static void set_timeout(int sock, int timeout) {
195 #ifdef _WIN32
196         DWORD tv = timeout;
197 #else
198         struct timeval tv;
199         tv.tv_sec = timeout / 1000;
200         tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
201 #endif
202         setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
203         setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
204 }
205
206 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
207         char *hostname = NULL;
208
209         logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
210         struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
211         struct addrinfo *aip = ai;
212         static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
213         char line[256];
214
215         while(aip) {
216                 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
217                 if(s >= 0) {
218                         set_timeout(s, 5000);
219                         if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
220                                 closesocket(s);
221                                 s = -1;
222                         }
223                 }
224                 if(s >= 0) {
225                         send(s, request, sizeof request - 1, 0);
226                         int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
227                         if(len > 0) {
228                                 line[len] = 0;
229                                 if(line[len - 1] == '\n')
230                                         line[--len] = 0;
231                                 char *p = strrchr(line, '\n');
232                                 if(p && p[1])
233                                         hostname = xstrdup(p + 1);
234                         }
235                         closesocket(s);
236                         if(hostname)
237                                 break;
238                 }
239                 aip = aip->ai_next;
240                 continue;
241         }
242
243         if(ai)
244                 freeaddrinfo(ai);
245
246         // Check that the hostname is reasonable
247         if(hostname && !is_valid_hostname(hostname)) {
248                 free(hostname);
249                 hostname = NULL;
250         }
251
252         if(!hostname)
253                 meshlink_errno = MESHLINK_ERESOLV;
254
255         return hostname;
256 }
257
258 static char *get_my_hostname(meshlink_handle_t* mesh) {
259         char *hostname = NULL;
260         char *port = NULL;
261         char *hostport = NULL;
262         char *name = mesh->self->name;
263         char filename[PATH_MAX] = "";
264         FILE *f;
265
266         // Use first Address statement in own host config file
267         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
268         scan_for_hostname(filename, &hostname, &port);
269
270         if(hostname)
271                 goto done;
272
273         hostname = meshlink_get_external_address(mesh);
274         if(!hostname)
275                 return NULL;
276
277         f = fopen(filename, "a");
278         if(f) {
279                 fprintf(f, "\nAddress = %s\n", hostname);
280                 fclose(f);
281         } else {
282                 logger(mesh, MESHLINK_DEBUG, "Could not append Address to %s: %s\n", filename, strerror(errno));
283         }
284
285 done:
286         if(port) {
287                 if(strchr(hostname, ':'))
288                         xasprintf(&hostport, "[%s]:%s", hostname, port);
289                 else
290                         xasprintf(&hostport, "%s:%s", hostname, port);
291         } else {
292                 if(strchr(hostname, ':'))
293                         xasprintf(&hostport, "[%s]", hostname);
294                 else
295                         hostport = xstrdup(hostname);
296         }
297
298         free(hostname);
299         free(port);
300         return hostport;
301 }
302
303 static char *get_line(const char **data) {
304         if(!data || !*data)
305                 return NULL;
306
307         if(!**data) {
308                 *data = NULL;
309                 return NULL;
310         }
311
312         static char line[1024];
313         const char *end = strchr(*data, '\n');
314         size_t len = end ? end - *data : strlen(*data);
315         if(len >= sizeof line) {
316                 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
317                 return NULL;
318         }
319         if(len && !isprint(**data))
320                 abort();
321
322         memcpy(line, *data, len);
323         line[len] = 0;
324
325         if(end)
326                 *data = end + 1;
327         else
328                 *data = NULL;
329
330         return line;
331 }
332
333 static char *get_value(const char *data, const char *var) {
334         char *line = get_line(&data);
335         if(!line)
336                 return NULL;
337
338         char *sep = line + strcspn(line, " \t=");
339         char *val = sep + strspn(sep, " \t");
340         if(*val == '=')
341                 val += 1 + strspn(val + 1, " \t");
342         *sep = 0;
343         if(strcasecmp(line, var))
344                 return NULL;
345         return val;
346 }
347
348 static bool try_bind(int port) {
349         struct addrinfo *ai = NULL;
350         struct addrinfo hint = {
351                 .ai_flags = AI_PASSIVE,
352                 .ai_family = AF_UNSPEC,
353                 .ai_socktype = SOCK_STREAM,
354                 .ai_protocol = IPPROTO_TCP,
355         };
356
357         char portstr[16];
358         snprintf(portstr, sizeof portstr, "%d", port);
359
360         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
361                 return false;
362
363         while(ai) {
364                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
365                 if(!fd) {
366                         freeaddrinfo(ai);
367                         return false;
368                 }
369                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
370                 closesocket(fd);
371                 if(result) {
372                         freeaddrinfo(ai);
373                         return false;
374                 }
375                 ai = ai->ai_next;
376         }
377
378         freeaddrinfo(ai);
379         return true;
380 }
381
382 static int check_port(meshlink_handle_t *mesh) {
383         for(int i = 0; i < 1000; i++) {
384                 int port = 0x1000 + (rand() & 0x7fff);
385                 if(try_bind(port)) {
386                         char filename[PATH_MAX];
387                         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
388                         FILE *f = fopen(filename, "a");
389                         if(!f) {
390                                 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
391                                 return 0;
392                         }
393
394                         fprintf(f, "Port = %d\n", port);
395                         fclose(f);
396                         return port;
397                 }
398         }
399
400         logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
401         return 0;
402 }
403
404 static bool finalize_join(meshlink_handle_t *mesh) {
405         char *name = xstrdup(get_value(mesh->data, "Name"));
406         if(!name) {
407                 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
408                 return false;
409         }
410
411         if(!check_id(name)) {
412                 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
413                 return false;
414         }
415
416         char filename[PATH_MAX];
417         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
418
419         FILE *f = fopen(filename, "w");
420         if(!f) {
421                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
422                 return false;
423         }
424
425         fprintf(f, "Name = %s\n", name);
426
427         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
428         FILE *fh = fopen(filename, "w");
429         if(!fh) {
430                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
431                 fclose(f);
432                 return false;
433         }
434
435         // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
436         // Other chunks go unfiltered to their respective host config files
437         const char *p = mesh->data;
438         char *l, *value;
439
440         while((l = get_line(&p))) {
441                 // Ignore comments
442                 if(*l == '#')
443                         continue;
444
445                 // Split line into variable and value
446                 int len = strcspn(l, "\t =");
447                 value = l + len;
448                 value += strspn(value, "\t ");
449                 if(*value == '=') {
450                         value++;
451                         value += strspn(value, "\t ");
452                 }
453                 l[len] = 0;
454
455                 // Is it a Name?
456                 if(!strcasecmp(l, "Name"))
457                         if(strcmp(value, name))
458                                 break;
459                         else
460                                 continue;
461                 else if(!strcasecmp(l, "NetName"))
462                         continue;
463
464                 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
465                 bool found = false;
466                 int i;
467                 for(i = 0; variables[i].name; i++) {
468                         if(strcasecmp(l, variables[i].name))
469                                 continue;
470                         found = true;
471                         break;
472                 }
473
474                 // Ignore unknown and unsafe variables
475                 if(!found) {
476                         logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
477                         continue;
478                 } else if(!(variables[i].type & VAR_SAFE)) {
479                         logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
480                         continue;
481                 }
482
483                 // Copy the safe variable to the right config file
484                 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
485         }
486
487         fclose(f);
488
489         while(l && !strcasecmp(l, "Name")) {
490                 if(!check_id(value)) {
491                         logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
492                         return false;
493                 }
494
495                 if(!strcmp(value, name)) {
496                         logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
497                         return false;
498                 }
499
500                 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
501                 f = fopen(filename, "w");
502
503                 if(!f) {
504                         logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
505                         return false;
506                 }
507
508                 while((l = get_line(&p))) {
509                         if(!strcmp(l, "#---------------------------------------------------------------#"))
510                                 continue;
511                         int len = strcspn(l, "\t =");
512                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
513                                 value = l + len;
514                                 value += strspn(value, "\t ");
515                                 if(*value == '=') {
516                                         value++;
517                                         value += strspn(value, "\t ");
518                                 }
519                                 l[len] = 0;
520                                 break;
521                         }
522
523                         fputs(l, f);
524                         fputc('\n', f);
525                 }
526
527                 fclose(f);
528         }
529
530         char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
531         if(!b64key) {
532                 fclose(fh);
533                 return false;
534                 }
535
536         fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
537         fprintf(fh, "Port = %s\n", mesh->myport);
538
539         fclose(fh);
540
541         sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
542         free(b64key);
543
544         free(mesh->self->name);
545         free(mesh->self->connection->name);
546         mesh->self->name = xstrdup(name);
547         mesh->self->connection->name = name;
548
549         logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
550
551         load_all_nodes(mesh);
552
553         return true;
554 }
555
556 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
557         meshlink_handle_t* mesh = handle;
558         while(len) {
559                 int result = send(mesh->sock, data, len, 0);
560                 if(result == -1 && errno == EINTR)
561                         continue;
562                 else if(result <= 0)
563                         return false;
564                 data += result;
565                 len -= result;
566         }
567         return true;
568 }
569
570 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
571         meshlink_handle_t* mesh = handle;
572         switch(type) {
573                 case SPTPS_HANDSHAKE:
574                         return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
575
576                 case 0:
577                         mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
578                         memcpy(mesh->data + mesh->thedatalen, msg, len);
579                         mesh->thedatalen += len;
580                         mesh->data[mesh->thedatalen] = 0;
581                         break;
582
583                 case 1:
584                         mesh->thedatalen = 0;
585                         return finalize_join(mesh);
586
587                 case 2:
588                         logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
589                         shutdown(mesh->sock, SHUT_RDWR);
590                         mesh->success = true;
591                         break;
592
593                 default:
594                         return false;
595         }
596
597         return true;
598 }
599
600 static bool recvline(meshlink_handle_t* mesh, size_t len) {
601         char *newline = NULL;
602
603         if(!mesh->sock)
604                 abort();
605
606         while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
607                 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
608                 if(result == -1 && errno == EINTR)
609                         continue;
610                 else if(result <= 0)
611                         return false;
612                 mesh->blen += result;
613         }
614
615         if(newline - mesh->buffer >= len)
616                 return false;
617
618         len = newline - mesh->buffer;
619
620         memcpy(mesh->line, mesh->buffer, len);
621         mesh->line[len] = 0;
622         memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
623         mesh->blen -= len + 1;
624
625         return true;
626 }
627 static bool sendline(int fd, char *format, ...) {
628         static char buffer[4096];
629         char *p = buffer;
630         int blen = 0;
631         va_list ap;
632
633         va_start(ap, format);
634         blen = vsnprintf(buffer, sizeof buffer, format, ap);
635         va_end(ap);
636
637         if(blen < 1 || blen >= sizeof buffer)
638                 return false;
639
640         buffer[blen] = '\n';
641         blen++;
642
643         while(blen) {
644                 int result = send(fd, p, blen, MSG_NOSIGNAL);
645                 if(result == -1 && errno == EINTR)
646                         continue;
647                 else if(result <= 0)
648                         return false;
649                 p += result;
650                 blen -= result;
651         }
652
653         return true;
654 }
655
656 static const char *errstr[] = {
657         [MESHLINK_OK] = "No error",
658         [MESHLINK_EINVAL] = "Invalid argument",
659         [MESHLINK_ENOMEM] = "Out of memory",
660         [MESHLINK_ENOENT] = "No such node",
661         [MESHLINK_EEXIST] = "Node already exists",
662         [MESHLINK_EINTERNAL] = "Internal error",
663         [MESHLINK_ERESOLV] = "Could not resolve hostname",
664         [MESHLINK_ESTORAGE] = "Storage error",
665         [MESHLINK_ENETWORK] = "Network error",
666         [MESHLINK_EPEER] = "Error communicating with peer",
667 };
668
669 const char *meshlink_strerror(meshlink_errno_t err) {
670         if(err < 0 || err >= sizeof errstr / sizeof *errstr)
671                 return "Invalid error code";
672         return errstr[err];
673 }
674
675 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
676         ecdsa_t *key;
677         FILE *f;
678         char pubname[PATH_MAX], privname[PATH_MAX];
679
680         logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
681
682         if(!(key = ecdsa_generate())) {
683                 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
684                 meshlink_errno = MESHLINK_EINTERNAL;
685                 return false;
686         } else
687                 logger(mesh, MESHLINK_DEBUG, "Done.\n");
688
689         snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
690         f = fopen(privname, "wb");
691
692         if(!f) {
693                 meshlink_errno = MESHLINK_ESTORAGE;
694                 return false;
695         }
696
697 #ifdef HAVE_FCHMOD
698         fchmod(fileno(f), 0600);
699 #endif
700
701         if(!ecdsa_write_pem_private_key(key, f)) {
702                 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
703                 ecdsa_free(key);
704                 fclose(f);
705                 meshlink_errno = MESHLINK_EINTERNAL;
706                 return false;
707         }
708
709         fclose(f);
710
711         snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
712         f = fopen(pubname, "a");
713
714         if(!f) {
715                 meshlink_errno = MESHLINK_ESTORAGE;
716                 return false;
717         }
718
719         char *pubkey = ecdsa_get_base64_public_key(key);
720         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
721         free(pubkey);
722
723         fclose(f);
724         ecdsa_free(key);
725
726         return true;
727 }
728
729 static struct timeval idle(event_loop_t *loop, void *data) {
730         meshlink_handle_t *mesh = data;
731         struct timeval t, tmin = {3600, 0};
732         for splay_each(node_t, n, mesh->nodes) {
733                 if(!n->utcp)
734                         continue;
735                 t = utcp_timeout(n->utcp);
736                 if(timercmp(&t, &tmin, <))
737                         tmin = t;
738         }
739         return tmin;
740 }
741
742 // Find out what local address a socket would use if we connect to the given address.
743 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
744 // of both endpoints, but this will actually not send any UDP packet.
745 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
746         struct addrinfo *rai = NULL;
747         const struct addrinfo hint = {
748                 .ai_family = AF_UNSPEC,
749                 .ai_socktype = SOCK_DGRAM,
750                 .ai_protocol = IPPROTO_UDP,
751         };
752
753         if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai)
754                 return false;
755
756         int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
757         if(sock == -1) {
758                 freeaddrinfo(rai);
759                 return false;
760         }
761
762         if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
763                 freeaddrinfo(rai);
764                 return false;
765         }
766
767         freeaddrinfo(rai);
768
769         struct sockaddr_storage sn;
770         socklen_t sl = sizeof sn;
771
772         if(getsockname(sock, (struct sockaddr *)&sn, &sl))
773                 return false;
774
775         if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV))
776                 return false;
777
778         return true;
779 }
780
781 // Get our local address(es) by simulating connecting to an Internet host.
782 static void add_local_addresses(meshlink_handle_t *mesh) {
783         char host[NI_MAXHOST];
784         char entry[MAX_STRING_SIZE];
785
786         // IPv4 example.org
787
788         if(getlocaladdrname("93.184.216.34", host, sizeof host)) {
789                 snprintf(entry, sizeof entry, "%s %s", host, mesh->myport);
790                 append_config_file(mesh, mesh->name, "Address", entry);
791         }
792
793         // IPv6 example.org
794
795         if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof host)) {
796                 snprintf(entry, sizeof entry, "%s %s", host, mesh->myport);
797                 append_config_file(mesh, mesh->name, "Address", entry);
798         }
799 }
800
801 static bool meshlink_setup(meshlink_handle_t *mesh) {
802         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
803                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
804                 meshlink_errno = MESHLINK_ESTORAGE;
805                 return false;
806         }
807
808         char filename[PATH_MAX];
809         snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
810
811         if(mkdir(filename, 0777) && errno != EEXIST) {
812                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
813                 meshlink_errno = MESHLINK_ESTORAGE;
814                 return false;
815         }
816
817         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
818
819         if(!access(filename, F_OK)) {
820                 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
821                 meshlink_errno = MESHLINK_EEXIST;
822                 return false;
823         }
824
825         FILE *f = fopen(filename, "w");
826         if(!f) {
827                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
828                 meshlink_errno = MESHLINK_ESTORAGE;
829                 return false;
830         }
831
832         fprintf(f, "Name = %s\n", mesh->name);
833         fclose(f);
834
835         if(!ecdsa_keygen(mesh)) {
836                 meshlink_errno = MESHLINK_EINTERNAL;
837                 return false;
838         }
839
840         check_port(mesh);
841
842         return true;
843 }
844
845 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
846         // Validate arguments provided by the application
847         bool usingname = false;
848         
849         logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
850
851         if(!confbase || !*confbase) {
852                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
853                 meshlink_errno = MESHLINK_EINVAL;
854                 return NULL;
855         }
856
857         if(!appname || !*appname) {
858                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
859                 meshlink_errno = MESHLINK_EINVAL;
860                 return NULL;
861         }
862
863         if(!name || !*name) {
864                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
865                 //return NULL;
866         }
867         else { //check name only if there is a name != NULL
868
869                 if(!check_id(name)) {
870                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
871                         meshlink_errno = MESHLINK_EINVAL;
872                         return NULL;
873                 } else { usingname = true;}
874         }
875
876         if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
877                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
878                 meshlink_errno = MESHLINK_EINVAL;
879                 return NULL;
880         }
881
882         meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
883         mesh->confbase = xstrdup(confbase);
884         mesh->appname = xstrdup(appname);
885         mesh->devclass = devclass;
886         if (usingname) mesh->name = xstrdup(name);
887
888         // initialize mutex
889         pthread_mutexattr_t attr;
890         pthread_mutexattr_init(&attr);
891         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
892         pthread_mutex_init(&(mesh->mesh_mutex), &attr);
893         
894         mesh->threadstarted = false;
895         event_loop_init(&mesh->loop);
896         mesh->loop.data = mesh;
897
898         // Check whether meshlink.conf already exists
899
900         char filename[PATH_MAX];
901         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
902
903         if(access(filename, R_OK)) {
904                 if(errno == ENOENT) {
905                         // If not, create it
906                         if(!meshlink_setup(mesh)) {
907                                 // meshlink_errno is set by meshlink_setup()
908                                 return NULL;
909                         }
910                 } else {
911                         logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
912                         meshlink_close(mesh);
913                         meshlink_errno = MESHLINK_ESTORAGE;
914                         return NULL;
915                 }
916         }
917
918         // Read the configuration
919
920         init_configuration(&mesh->config);
921
922         if(!read_server_config(mesh)) {
923                 meshlink_close(mesh);
924                 meshlink_errno = MESHLINK_ESTORAGE;
925                 return NULL;
926         };
927
928 #ifdef HAVE_MINGW
929         struct WSAData wsa_state;
930         WSAStartup(MAKEWORD(2, 2), &wsa_state);
931 #endif
932
933         // Setup up everything
934         // TODO: we should not open listening sockets yet
935
936         if(!setup_network(mesh)) {
937                 meshlink_close(mesh);
938                 meshlink_errno = MESHLINK_ENETWORK;
939                 return NULL;
940         }
941
942         add_local_addresses(mesh);
943
944         idle_set(&mesh->loop, idle, mesh);
945
946         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
947         return mesh;
948 }
949
950 static void *meshlink_main_loop(void *arg) {
951         meshlink_handle_t *mesh = arg;
952
953         pthread_mutex_lock(&(mesh->mesh_mutex));
954
955         try_outgoing_connections(mesh);
956
957         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
958         main_loop(mesh);
959         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
960
961         pthread_mutex_unlock(&(mesh->mesh_mutex));
962         return NULL;
963 }
964
965 bool meshlink_start(meshlink_handle_t *mesh) {
966         if(!mesh) {
967                 meshlink_errno = MESHLINK_EINVAL;
968                 return false;
969         }
970         
971         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
972
973         pthread_mutex_lock(&(mesh->mesh_mutex));
974
975         if(mesh->threadstarted) {
976                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
977                 pthread_mutex_unlock(&(mesh->mesh_mutex));
978                 return true;
979         }
980
981         if(mesh->listen_socket[0].tcp.fd < 0) {
982                 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
983                 meshlink_errno = MESHLINK_ENETWORK;
984                 return false;
985         }
986
987         mesh->thedatalen = 0;
988
989         // TODO: open listening sockets first
990
991         //Check that a valid name is set
992         if(!mesh->name ) {
993                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
994                 meshlink_errno = MESHLINK_EINVAL;
995                 pthread_mutex_unlock(&(mesh->mesh_mutex));
996                 return false;
997         }
998
999         // Start the main thread
1000
1001         event_loop_start(&mesh->loop);
1002
1003         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1004                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1005                 memset(&mesh->thread, 0, sizeof mesh->thread);
1006                 meshlink_errno = MESHLINK_EINTERNAL;
1007                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1008                 return false;
1009         }
1010
1011         mesh->threadstarted=true;
1012
1013         discovery_start(mesh);
1014
1015         pthread_mutex_unlock(&(mesh->mesh_mutex));
1016         return true;
1017 }
1018
1019 void meshlink_stop(meshlink_handle_t *mesh) {
1020         if(!mesh) {
1021                 meshlink_errno = MESHLINK_EINVAL;
1022                 return;
1023         }
1024
1025         pthread_mutex_lock(&(mesh->mesh_mutex));
1026         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1027
1028         // Stop discovery
1029         discovery_stop(mesh);
1030
1031         // Shut down the main thread
1032         event_loop_stop(&mesh->loop);
1033
1034         // Send ourselves a UDP packet to kick the event loop
1035         listen_socket_t *s = &mesh->listen_socket[0];
1036         if(sendto(s->udp.fd, "", 1, MSG_NOSIGNAL, &s->sa.sa, SALEN(s->sa.sa)) == -1)
1037                 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself");
1038
1039         // Wait for the main thread to finish
1040         pthread_mutex_unlock(&(mesh->mesh_mutex));
1041         pthread_join(mesh->thread, NULL);
1042         pthread_mutex_lock(&(mesh->mesh_mutex));
1043
1044         mesh->threadstarted = false;
1045
1046         pthread_mutex_unlock(&(mesh->mesh_mutex));
1047 }
1048
1049 void meshlink_close(meshlink_handle_t *mesh) {
1050         if(!mesh || !mesh->confbase) {
1051                 meshlink_errno = MESHLINK_EINVAL;
1052                 return;
1053         }
1054
1055         // stop can be called even if mesh has not been started
1056         meshlink_stop(mesh);
1057
1058         // lock is not released after this
1059         pthread_mutex_lock(&(mesh->mesh_mutex));
1060
1061         // Close and free all resources used.
1062
1063         close_network_connections(mesh);
1064
1065         logger(mesh, MESHLINK_INFO, "Terminating");
1066
1067         exit_configuration(&mesh->config);
1068         event_loop_exit(&mesh->loop);
1069
1070 #ifdef HAVE_MINGW
1071         if(mesh->confbase)
1072                 WSACleanup();
1073 #endif
1074
1075         ecdsa_free(mesh->invitation_key);
1076
1077         free(mesh->name);
1078         free(mesh->appname);
1079         free(mesh->confbase);
1080         pthread_mutex_destroy(&(mesh->mesh_mutex));
1081
1082         memset(mesh, 0, sizeof *mesh);
1083
1084         free(mesh);
1085 }
1086
1087 static void deltree(const char *dirname) {
1088         DIR *d = opendir(dirname);
1089         if(d) {
1090                 struct dirent *ent;
1091                 while((ent = readdir(d))) {
1092                         if(ent->d_name[0] == '.')
1093                                 continue;
1094                         char filename[PATH_MAX];
1095                         snprintf(filename, sizeof filename, "%s" SLASH "%s", dirname, ent->d_name);
1096                         if(unlink(filename))
1097                                 deltree(filename);
1098                 }
1099                 closedir(d);
1100         }
1101         rmdir(dirname);
1102         return;
1103 }
1104
1105 bool meshlink_destroy(const char *confbase) {
1106         if(!confbase) {
1107                 meshlink_errno = MESHLINK_EINVAL;
1108                 return false;
1109         }
1110
1111         char filename[PATH_MAX];
1112         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
1113
1114         if(unlink(filename)) {
1115                 if(errno == ENOENT) {
1116                         meshlink_errno = MESHLINK_ENOENT;
1117                         return false;
1118                 } else {
1119                         logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1120                         meshlink_errno = MESHLINK_ESTORAGE;
1121                         return false;
1122                 }
1123         }
1124
1125         deltree(confbase);
1126
1127         return true;
1128 }
1129
1130 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1131         if(!mesh) {
1132                 meshlink_errno = MESHLINK_EINVAL;
1133                 return;
1134         }
1135
1136         pthread_mutex_lock(&(mesh->mesh_mutex));
1137         mesh->receive_cb = cb;
1138         pthread_mutex_unlock(&(mesh->mesh_mutex));
1139 }
1140
1141 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1142         if(!mesh) {
1143                 meshlink_errno = MESHLINK_EINVAL;
1144                 return;
1145         }
1146
1147         pthread_mutex_lock(&(mesh->mesh_mutex));
1148         mesh->node_status_cb = cb;
1149         pthread_mutex_unlock(&(mesh->mesh_mutex));
1150 }
1151
1152 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1153         if(mesh) {
1154                 pthread_mutex_lock(&(mesh->mesh_mutex));
1155                 mesh->log_cb = cb;
1156                 mesh->log_level = cb ? level : 0;
1157                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1158         } else {
1159                 global_log_cb = cb;
1160                 global_log_level = cb ? level : 0;
1161         }
1162 }
1163
1164 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1165         meshlink_packethdr_t *hdr;
1166
1167         // Validate arguments
1168         if(!mesh || !destination || len >= MAXSIZE - sizeof *hdr) {
1169                 meshlink_errno = MESHLINK_EINVAL;
1170                 return false;
1171         }
1172
1173         if(!len)
1174                 return true;
1175
1176         if(!data) {
1177                 meshlink_errno = MESHLINK_EINVAL;
1178                 return false;
1179         }
1180
1181         // Prepare the packet
1182         vpn_packet_t *packet = malloc(sizeof *packet);
1183         if(!packet) {
1184                 meshlink_errno = MESHLINK_ENOMEM;
1185                 return false;
1186         }
1187
1188         packet->probe = false;
1189         packet->tcp = false;
1190         packet->len = len + sizeof *hdr;
1191
1192         hdr = (meshlink_packethdr_t *)packet->data;
1193         memset(hdr, 0, sizeof *hdr);
1194         // leave the last byte as 0 to make sure strings are always
1195         // null-terminated if they are longer than the buffer
1196         strncpy(hdr->destination, destination->name, (sizeof hdr->destination) - 1);
1197         strncpy(hdr->source, mesh->self->name, (sizeof hdr->source) -1 );
1198
1199         memcpy(packet->data + sizeof *hdr, data, len);
1200
1201         // Queue it
1202         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1203                 free(packet);
1204                 meshlink_errno = MESHLINK_ENOMEM;
1205                 return false;
1206         }
1207
1208         // Notify event loop
1209         signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1210         
1211         return true;
1212 }
1213
1214 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1215         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1216         if(!packet)
1217                 return;
1218
1219         mesh->self->in_packets++;
1220         mesh->self->in_bytes += packet->len;
1221         route(mesh, mesh->self, packet);
1222 }
1223
1224 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1225         if(!mesh || !destination) {
1226                 meshlink_errno = MESHLINK_EINVAL;
1227                 return -1;
1228         }
1229         pthread_mutex_lock(&(mesh->mesh_mutex));
1230
1231         node_t *n = (node_t *)destination;
1232         if(!n->status.reachable) {
1233                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1234                 return 0;
1235         
1236         }
1237         else if(n->mtuprobes > 30 && n->minmtu) {
1238                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1239                 return n->minmtu;
1240         }
1241         else {
1242                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1243                 return MTU;
1244         }
1245 }
1246
1247 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1248         if(!mesh || !node) {
1249                 meshlink_errno = MESHLINK_EINVAL;
1250                 return NULL;
1251         }
1252         pthread_mutex_lock(&(mesh->mesh_mutex));
1253
1254         node_t *n = (node_t *)node;
1255
1256         if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1257                 meshlink_errno = MESHLINK_EINTERNAL;
1258                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1259                 return false;
1260         }
1261
1262         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1263
1264         if(!fingerprint)
1265                 meshlink_errno = MESHLINK_EINTERNAL;
1266
1267         pthread_mutex_unlock(&(mesh->mesh_mutex));
1268         return fingerprint;
1269 }
1270
1271 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1272         if(!mesh) {
1273                 meshlink_errno = MESHLINK_EINVAL;
1274                 return NULL;
1275         }
1276
1277         return (meshlink_node_t *)mesh->self;
1278 }
1279
1280 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1281         if(!mesh || !name) {
1282                 meshlink_errno = MESHLINK_EINVAL;
1283                 return NULL;
1284         }
1285
1286         meshlink_node_t *node = NULL;
1287
1288         pthread_mutex_lock(&(mesh->mesh_mutex));
1289         node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1290         pthread_mutex_unlock(&(mesh->mesh_mutex));
1291         return node;
1292 }
1293
1294 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1295         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1296                 meshlink_errno = MESHLINK_EINVAL;
1297                 return NULL;
1298         }
1299
1300         meshlink_node_t **result;
1301
1302         //lock mesh->nodes
1303         pthread_mutex_lock(&(mesh->mesh_mutex));
1304
1305         *nmemb = mesh->nodes->count;
1306         result = realloc(nodes, *nmemb * sizeof *nodes);
1307
1308         if(result) {
1309                 meshlink_node_t **p = result;
1310                 for splay_each(node_t, n, mesh->nodes)
1311                         *p++ = (meshlink_node_t *)n;
1312         } else {
1313                 *nmemb = 0;
1314                 free(nodes);
1315                 meshlink_errno = MESHLINK_ENOMEM;
1316         }
1317
1318         pthread_mutex_unlock(&(mesh->mesh_mutex));
1319
1320         return result;
1321 }
1322
1323 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1324         if(!mesh || !data || !len || !signature || !siglen) {
1325                 meshlink_errno = MESHLINK_EINVAL;
1326                 return false;
1327         }
1328
1329         if(*siglen < MESHLINK_SIGLEN) {
1330                 meshlink_errno = MESHLINK_EINVAL;
1331                 return false;
1332         }
1333
1334         pthread_mutex_lock(&(mesh->mesh_mutex));
1335
1336         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1337                 meshlink_errno = MESHLINK_EINTERNAL;
1338                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1339                 return false;
1340         }
1341
1342         *siglen = MESHLINK_SIGLEN;
1343         pthread_mutex_unlock(&(mesh->mesh_mutex));
1344         return true;
1345 }
1346
1347 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1348         if(!mesh || !data || !len || !signature) {
1349                 meshlink_errno = MESHLINK_EINVAL;
1350                 return false;
1351         }
1352
1353         if(siglen != MESHLINK_SIGLEN) {
1354                 meshlink_errno = MESHLINK_EINVAL;
1355                 return false;
1356         }
1357
1358         pthread_mutex_lock(&(mesh->mesh_mutex));
1359
1360         bool rval = false;
1361
1362         struct node_t *n = (struct node_t *)source;
1363         node_read_ecdsa_public_key(mesh, n);
1364         if(!n->ecdsa) {
1365                 meshlink_errno = MESHLINK_EINTERNAL;
1366                 rval = false;
1367         } else {
1368                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1369         }
1370         pthread_mutex_unlock(&(mesh->mesh_mutex));
1371         return rval;
1372 }
1373
1374 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1375         char filename[PATH_MAX];
1376         
1377         pthread_mutex_lock(&(mesh->mesh_mutex));
1378
1379         snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1380         if(mkdir(filename, 0700) && errno != EEXIST) {
1381                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1382                 meshlink_errno = MESHLINK_ESTORAGE;
1383                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1384                 return false;
1385         }
1386
1387         // Count the number of valid invitations, clean up old ones
1388         DIR *dir = opendir(filename);
1389         if(!dir) {
1390                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1391                 meshlink_errno = MESHLINK_ESTORAGE;
1392                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1393                 return false;
1394         }
1395
1396         errno = 0;
1397         int count = 0;
1398         struct dirent *ent;
1399         time_t deadline = time(NULL) - 604800; // 1 week in the past
1400
1401         while((ent = readdir(dir))) {
1402                 if(strlen(ent->d_name) != 24)
1403                         continue;
1404                 char invname[PATH_MAX];
1405                 struct stat st;
1406                 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1407                 if(!stat(invname, &st)) {
1408                         if(mesh->invitation_key && deadline < st.st_mtime)
1409                                 count++;
1410                         else
1411                                 unlink(invname);
1412                 } else {
1413                         logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1414                         errno = 0;
1415                 }
1416         }
1417
1418         if(errno) {
1419                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1420                 closedir(dir);
1421                 meshlink_errno = MESHLINK_ESTORAGE;
1422                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1423                 return false;
1424         }
1425
1426         closedir(dir);
1427
1428         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1429
1430         // Remove the key if there are no outstanding invitations.
1431         if(!count) {
1432                 unlink(filename);
1433                 if(mesh->invitation_key) {
1434                         ecdsa_free(mesh->invitation_key);
1435                         mesh->invitation_key = NULL;
1436                 }
1437         }
1438
1439         if(mesh->invitation_key) {
1440                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1441                 return true;
1442         }
1443
1444         // Create a new key if necessary.
1445         FILE *f = fopen(filename, "rb");
1446         if(!f) {
1447                 if(errno != ENOENT) {
1448                         logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1449                         meshlink_errno = MESHLINK_ESTORAGE;
1450                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1451                         return false;
1452                 }
1453
1454                 mesh->invitation_key = ecdsa_generate();
1455                 if(!mesh->invitation_key) {
1456                         logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1457                         meshlink_errno = MESHLINK_EINTERNAL;
1458                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1459                         return false;
1460                 }
1461                 f = fopen(filename, "wb");
1462                 if(!f) {
1463                         logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1464                         meshlink_errno = MESHLINK_ESTORAGE;
1465                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1466                         return false;
1467                 }
1468                 chmod(filename, 0600);
1469                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1470                 fclose(f);
1471         } else {
1472                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1473                 fclose(f);
1474                 if(!mesh->invitation_key) {
1475                         logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1476                         meshlink_errno = MESHLINK_ESTORAGE;
1477                 }
1478         }
1479
1480         pthread_mutex_unlock(&(mesh->mesh_mutex));
1481         return mesh->invitation_key;
1482 }
1483
1484 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1485         if(!mesh || !address) {
1486                 meshlink_errno = MESHLINK_EINVAL;
1487                 return false;
1488         }
1489
1490         if(!is_valid_hostname(address)) {
1491                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1492                 meshlink_errno = MESHLINK_EINVAL;
1493                 return false;
1494         }
1495
1496         bool rval = false;
1497
1498         pthread_mutex_lock(&(mesh->mesh_mutex));
1499         rval = append_config_file(mesh, mesh->self->name, "Address", address);
1500         pthread_mutex_unlock(&(mesh->mesh_mutex));
1501
1502         return rval;
1503 }
1504
1505 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1506         if(!mesh) {
1507                 meshlink_errno = MESHLINK_EINVAL;
1508                 return false;
1509         }
1510
1511         char *address = meshlink_get_external_address(mesh);
1512         if(!address)
1513                 return false;
1514
1515         bool rval = false;
1516
1517         pthread_mutex_lock(&(mesh->mesh_mutex));
1518         rval = append_config_file(mesh, mesh->self->name, "Address", address);
1519         pthread_mutex_unlock(&(mesh->mesh_mutex));
1520
1521         free(address);
1522         return rval;
1523 }
1524
1525 int meshlink_get_port(meshlink_handle_t *mesh) {
1526         if(!mesh) {
1527                 meshlink_errno = MESHLINK_EINVAL;
1528                 return -1;
1529         }
1530
1531         if(!mesh->myport) {
1532                 meshlink_errno = MESHLINK_EINTERNAL;
1533                 return -1;
1534         }
1535
1536         return atoi(mesh->myport);
1537 }
1538
1539 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1540         if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1541                 meshlink_errno = MESHLINK_EINVAL;
1542                 return false;
1543         }
1544
1545         if(mesh->myport && port == atoi(mesh->myport))
1546                 return true;
1547
1548         if(!try_bind(port)) {
1549                 meshlink_errno = MESHLINK_ENETWORK;
1550                 return false;
1551         }
1552
1553         bool rval = false;
1554
1555         pthread_mutex_lock(&(mesh->mesh_mutex));
1556         if(mesh->threadstarted) {
1557                 meshlink_errno = MESHLINK_EINVAL;
1558                 goto done;
1559         }
1560
1561         close_network_connections(mesh);
1562         exit_configuration(&mesh->config);
1563
1564         char portstr[10];
1565         snprintf(portstr, sizeof portstr, "%d", port);
1566         portstr[sizeof portstr - 1] = 0;
1567
1568         modify_config_file(mesh, mesh->name, "Port", portstr, true);
1569
1570         init_configuration(&mesh->config);
1571
1572         if(!read_server_config(mesh))
1573                 meshlink_errno = MESHLINK_ESTORAGE;
1574         else if(!setup_network(mesh))
1575                 meshlink_errno = MESHLINK_ENETWORK;
1576         else
1577                 rval = true;
1578
1579 done:
1580         pthread_mutex_unlock(&(mesh->mesh_mutex));
1581
1582         return rval;
1583 }
1584
1585 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1586         if(!mesh) {
1587                 meshlink_errno = MESHLINK_EINVAL;
1588                 return NULL;
1589         }
1590         
1591         pthread_mutex_lock(&(mesh->mesh_mutex));
1592
1593         // Check validity of the new node's name
1594         if(!check_id(name)) {
1595                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1596                 meshlink_errno = MESHLINK_EINVAL;
1597                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1598                 return NULL;
1599         }
1600
1601         // Ensure no host configuration file with that name exists
1602         char filename[PATH_MAX];
1603         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1604         if(!access(filename, F_OK)) {
1605                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1606                 meshlink_errno = MESHLINK_EEXIST;
1607                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1608                 return NULL;
1609         }
1610
1611         // Ensure no other nodes know about this name
1612         if(meshlink_get_node(mesh, name)) {
1613                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1614                 meshlink_errno = MESHLINK_EEXIST;
1615                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1616                 return NULL;
1617         }
1618
1619         // Get the local address
1620         char *address = get_my_hostname(mesh);
1621         if(!address) {
1622                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1623                 meshlink_errno = MESHLINK_ERESOLV;
1624                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1625                 return NULL;
1626         }
1627
1628         if(!refresh_invitation_key(mesh)) {
1629                 meshlink_errno = MESHLINK_EINTERNAL;
1630                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1631                 return NULL;
1632         }
1633
1634         char hash[64];
1635
1636         // Create a hash of the key.
1637         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1638         sha512(fingerprint, strlen(fingerprint), hash);
1639         b64encode_urlsafe(hash, hash, 18);
1640
1641         // Create a random cookie for this invitation.
1642         char cookie[25];
1643         randomize(cookie, 18);
1644
1645         // Create a filename that doesn't reveal the cookie itself
1646         char buf[18 + strlen(fingerprint)];
1647         char cookiehash[64];
1648         memcpy(buf, cookie, 18);
1649         memcpy(buf + 18, fingerprint, sizeof buf - 18);
1650         sha512(buf, sizeof buf, cookiehash);
1651         b64encode_urlsafe(cookiehash, cookiehash, 18);
1652
1653         b64encode_urlsafe(cookie, cookie, 18);
1654
1655         free(fingerprint);
1656
1657         // Create a file containing the details of the invitation.
1658         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1659         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1660         if(!ifd) {
1661                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1662                 meshlink_errno = MESHLINK_ESTORAGE;
1663                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1664                 return NULL;
1665         }
1666         FILE *f = fdopen(ifd, "w");
1667         if(!f)
1668                 abort();
1669
1670         // Fill in the details.
1671         fprintf(f, "Name = %s\n", name);
1672         //if(netname)
1673         //      fprintf(f, "NetName = %s\n", netname);
1674         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1675
1676         // Copy Broadcast and Mode
1677         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1678         FILE *tc = fopen(filename,  "r");
1679         if(tc) {
1680                 char buf[1024];
1681                 while(fgets(buf, sizeof buf, tc)) {
1682                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1683                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1684                                 fputs(buf, f);
1685                                 // Make sure there is a newline character.
1686                                 if(!strchr(buf, '\n'))
1687                                         fputc('\n', f);
1688                         }
1689                 }
1690                 fclose(tc);
1691         } else {
1692                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1693                 meshlink_errno = MESHLINK_ESTORAGE;
1694                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1695                 return NULL;
1696         }
1697
1698         fprintf(f, "#---------------------------------------------------------------#\n");
1699         fprintf(f, "Name = %s\n", mesh->self->name);
1700
1701         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1702         fcopy(f, filename);
1703         fclose(f);
1704
1705         // Create an URL from the local address, key hash and cookie
1706         char *url;
1707         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1708         free(address);
1709
1710         pthread_mutex_unlock(&(mesh->mesh_mutex));
1711         return url;
1712 }
1713
1714 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1715         if(!mesh || !invitation) {
1716                 meshlink_errno = MESHLINK_EINVAL;
1717                 return false;
1718         }
1719         
1720         pthread_mutex_lock(&(mesh->mesh_mutex));
1721
1722         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1723         char copy[strlen(invitation) + 1];
1724         strcpy(copy, invitation);
1725
1726         // Split the invitation URL into hostname, port, key hash and cookie.
1727
1728         char *slash = strchr(copy, '/');
1729         if(!slash)
1730                 goto invalid;
1731
1732         *slash++ = 0;
1733
1734         if(strlen(slash) != 48)
1735                 goto invalid;
1736
1737         char *address = copy;
1738         char *port = NULL;
1739         if(*address == '[') {
1740                 address++;
1741                 char *bracket = strchr(address, ']');
1742                 if(!bracket)
1743                         goto invalid;
1744                 *bracket = 0;
1745                 if(bracket[1] == ':')
1746                         port = bracket + 2;
1747         } else {
1748                 port = strchr(address, ':');
1749                 if(port)
1750                         *port++ = 0;
1751         }
1752
1753         if(!port)
1754                 goto invalid;
1755
1756         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1757                 goto invalid;
1758
1759         // Generate a throw-away key for the invitation.
1760         ecdsa_t *key = ecdsa_generate();
1761         if(!key) {
1762                 meshlink_errno = MESHLINK_EINTERNAL;
1763                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1764                 return false;
1765         }
1766
1767         char *b64key = ecdsa_get_base64_public_key(key);
1768
1769         //Before doing meshlink_join make sure we are not connected to another mesh
1770         if ( mesh->threadstarted ){
1771                 goto invalid;
1772         }
1773
1774         // Connect to the meshlink daemon mentioned in the URL.
1775         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1776         if(!ai) {
1777                 meshlink_errno = MESHLINK_ERESOLV;
1778                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1779                 return false;
1780         }
1781
1782         mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1783         if(mesh->sock <= 0) {
1784                 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1785                 freeaddrinfo(ai);
1786                 meshlink_errno = MESHLINK_ENETWORK;
1787                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1788                 return false;
1789         }
1790
1791         set_timeout(mesh->sock, 5000);
1792
1793         if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1794                 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1795                 closesocket(mesh->sock);
1796                 freeaddrinfo(ai);
1797                 meshlink_errno = MESHLINK_ENETWORK;
1798                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1799                 return false;
1800         }
1801
1802         freeaddrinfo(ai);
1803
1804         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1805
1806         // Tell him we have an invitation, and give him our throw-away key.
1807
1808         mesh->blen = 0;
1809
1810         if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1811                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1812                 closesocket(mesh->sock);
1813                 meshlink_errno = MESHLINK_ENETWORK;
1814                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1815                 return false;
1816         }
1817
1818         free(b64key);
1819
1820         char hisname[4096] = "";
1821         int code, hismajor, hisminor = 0;
1822
1823         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) {
1824                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1825                 closesocket(mesh->sock);
1826                 meshlink_errno = MESHLINK_ENETWORK;
1827                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1828                 return false;
1829         }
1830
1831         // Check if the hash of the key he gave us matches the hash in the URL.
1832         char *fingerprint = mesh->line + 2;
1833         char hishash[64];
1834         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1835                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1836                 meshlink_errno = MESHLINK_EINTERNAL;
1837                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1838                 return false;
1839         }
1840         if(memcmp(hishash, mesh->hash, 18)) {
1841                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1842                 meshlink_errno = MESHLINK_EPEER;
1843                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1844                 return false;
1845
1846         }
1847
1848         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1849         if(!hiskey) {
1850                 meshlink_errno = MESHLINK_EINTERNAL;
1851                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1852                 return false;
1853         }
1854
1855         // Start an SPTPS session
1856         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof meshlink_invitation_label, invitation_send, invitation_receive)) {
1857                 meshlink_errno = MESHLINK_EINTERNAL;
1858                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1859                 return false;
1860         }
1861
1862         // Feed rest of input buffer to SPTPS
1863         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1864                 meshlink_errno = MESHLINK_EPEER;
1865                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1866                 return false;
1867         }
1868
1869         int len;
1870
1871         while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1872                 if(len < 0) {
1873                         if(errno == EINTR)
1874                                 continue;
1875                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1876                         meshlink_errno = MESHLINK_ENETWORK;
1877                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1878                         return false;
1879                 }
1880
1881                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1882                         meshlink_errno = MESHLINK_EPEER;
1883                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1884                         return false;
1885                 }
1886         }
1887
1888         sptps_stop(&mesh->sptps);
1889         ecdsa_free(hiskey);
1890         ecdsa_free(key);
1891         closesocket(mesh->sock);
1892
1893         if(!mesh->success) {
1894                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1895                 meshlink_errno = MESHLINK_EPEER;
1896                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1897                 return false;
1898         }
1899
1900         pthread_mutex_unlock(&(mesh->mesh_mutex));
1901         return true;
1902
1903 invalid:
1904         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1905         meshlink_errno = MESHLINK_EINVAL;
1906         pthread_mutex_unlock(&(mesh->mesh_mutex));
1907         return false;
1908 }
1909
1910 char *meshlink_export(meshlink_handle_t *mesh) {
1911         if(!mesh) {
1912                 meshlink_errno = MESHLINK_EINVAL;
1913                 return NULL;
1914         }
1915
1916         pthread_mutex_lock(&(mesh->mesh_mutex));
1917         
1918         char filename[PATH_MAX];
1919         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1920         FILE *f = fopen(filename, "r");
1921         if(!f) {
1922                 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1923                 meshlink_errno = MESHLINK_ESTORAGE;
1924                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1925                 return NULL;
1926         }
1927
1928         fseek(f, 0, SEEK_END);
1929         int fsize = ftell(f);
1930         rewind(f);
1931
1932         size_t len = fsize + 9 + strlen(mesh->self->name);
1933         char *buf = xmalloc(len);
1934         snprintf(buf, len, "Name = %s\n", mesh->self->name);
1935         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1936                 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1937                 fclose(f);
1938                 meshlink_errno = MESHLINK_ESTORAGE;
1939                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1940                 return NULL;
1941         }
1942
1943         fclose(f);
1944         buf[len - 1] = 0;
1945         
1946         pthread_mutex_unlock(&(mesh->mesh_mutex));
1947         return buf;
1948 }
1949
1950 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1951         if(!mesh || !data) {
1952                 meshlink_errno = MESHLINK_EINVAL;
1953                 return false;
1954         }
1955         
1956         pthread_mutex_lock(&(mesh->mesh_mutex));
1957
1958         if(strncmp(data, "Name = ", 7)) {
1959                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1960                 meshlink_errno = MESHLINK_EPEER;
1961                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1962                 return false;
1963         }
1964
1965         char *end = strchr(data + 7, '\n');
1966         if(!end) {
1967                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1968                 meshlink_errno = MESHLINK_EPEER;
1969                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1970                 return false;
1971         }
1972
1973         int len = end - (data + 7);
1974         char name[len + 1];
1975         memcpy(name, data + 7, len);
1976         name[len] = 0;
1977         if(!check_id(name)) {
1978                 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1979                 meshlink_errno = MESHLINK_EPEER;
1980                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1981                 return false;
1982         }
1983
1984         char filename[PATH_MAX];
1985         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1986         if(!access(filename, F_OK)) {
1987                 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1988                 meshlink_errno = MESHLINK_EEXIST;
1989                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1990                 return false;
1991         }
1992
1993         if(errno != ENOENT) {
1994                 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1995                 meshlink_errno = MESHLINK_ESTORAGE;
1996                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1997                 return false;
1998         }
1999
2000         FILE *f = fopen(filename, "w");
2001         if(!f) {
2002                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2003                 meshlink_errno = MESHLINK_ESTORAGE;
2004                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2005                 return false;
2006         }
2007
2008         fwrite(end + 1, strlen(end + 1), 1, f);
2009         fclose(f);
2010
2011         load_all_nodes(mesh);
2012
2013         pthread_mutex_unlock(&(mesh->mesh_mutex));
2014         return true;
2015 }
2016
2017 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2018         if(!mesh || !node) {
2019                 meshlink_errno = MESHLINK_EINVAL;
2020                 return;
2021         }
2022
2023         pthread_mutex_lock(&(mesh->mesh_mutex));
2024         
2025         node_t *n;
2026         n = (node_t*)node;
2027         n->status.blacklisted=true;
2028         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n",node->name);
2029
2030         //Make blacklisting persistent in the config file
2031         append_config_file(mesh, n->name, "blacklisted", "yes");
2032
2033         pthread_mutex_unlock(&(mesh->mesh_mutex));
2034         return;
2035 }
2036
2037 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2038         if(!mesh || !node) {
2039                 meshlink_errno = MESHLINK_EINVAL;
2040                 return;
2041         }
2042
2043         pthread_mutex_lock(&(mesh->mesh_mutex));
2044         
2045         node_t *n = (node_t *)node;
2046         n->status.blacklisted = false;
2047
2048         //TODO: remove blacklisted = yes from the config file
2049
2050         pthread_mutex_unlock(&(mesh->mesh_mutex));
2051         return;
2052 }
2053
2054 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2055         mesh->default_blacklist = blacklist;
2056 }
2057
2058 /* Hint that a hostname may be found at an address
2059  * See header file for detailed comment.
2060  */
2061 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2062         if(!mesh || !node || !addr)
2063                 return;
2064
2065         // Ignore hints about ourself.
2066         if((node_t *)node == mesh->self)
2067                 return;
2068         
2069         pthread_mutex_lock(&(mesh->mesh_mutex));
2070         
2071         char *host = NULL, *port = NULL, *str = NULL;
2072         sockaddr2str((const sockaddr_t *)addr, &host, &port);
2073
2074         if(host && port) {
2075                 xasprintf(&str, "%s %s", host, port);
2076                 if ( (strncmp ("fe80",host,4) != 0) && ( strncmp("127.",host,4) != 0 ) && ( strcmp("localhost",host) !=0 ) )
2077                         append_config_file(mesh, node->name, "Address", str);
2078                 else
2079                         logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2080         }
2081
2082         free(str);
2083         free(host);
2084         free(port);
2085
2086         pthread_mutex_unlock(&(mesh->mesh_mutex));
2087         // @TODO do we want to fire off a connection attempt right away?
2088 }
2089
2090 /* Return an array of edges in the current network graph.
2091  * Data captures the current state and will not be updated.
2092  * Caller must deallocate data when done.
2093  */
2094 meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
2095         if(!mesh || !nmemb || (*nmemb && !edges)) {
2096                 meshlink_errno = MESHLINK_EINVAL;
2097                 return NULL;
2098         }
2099
2100         pthread_mutex_lock(&(mesh->mesh_mutex));
2101         
2102         meshlink_edge_t **result = NULL;
2103         meshlink_edge_t *copy = NULL;
2104         int result_size = 0;
2105
2106         result_size = mesh->edges->count;
2107
2108         // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
2109         if(result_size > *nmemb) {
2110                 result = realloc(edges, result_size * sizeof (meshlink_edge_t*));
2111         } else {
2112                 result = edges;
2113         }
2114
2115         if(result) {
2116                 meshlink_edge_t **p = result;
2117                 int n = 0;
2118                 for splay_each(edge_t, e, mesh->edges) {
2119                         // skip edges that do not represent a two-directional connection
2120                         if((!e->reverse) || (e->reverse->to != e->from)) {
2121                                 result_size--;
2122                                 continue;
2123                         }
2124                         n++;
2125                         // the first *nmemb members of result can be re-used
2126                         if(n > *nmemb) {
2127                                 copy = xzalloc(sizeof *copy);
2128                         }
2129                         else {
2130                                 copy = *p;
2131                         }
2132                         copy->from = (meshlink_node_t*)e->from;
2133                         copy->to = (meshlink_node_t*)e->to;
2134                         copy->address = e->address.storage;
2135                         copy->options = e->options;
2136                         copy->weight = e->weight;
2137                         *p++ = copy;
2138                 }
2139                 // shrink result to the actual amount of memory used
2140                 for(int i = *nmemb; i > result_size; i--) {
2141                         free(result[i - 1]);
2142                 }
2143                 result = realloc(result, result_size * sizeof (meshlink_edge_t*));
2144                 *nmemb = result_size;
2145         } else {
2146                 *nmemb = 0;
2147                 meshlink_errno = MESHLINK_ENOMEM;
2148         }
2149
2150         pthread_mutex_unlock(&(mesh->mesh_mutex));
2151
2152         return result;
2153 }
2154
2155 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2156         //TODO: implement
2157         return true;
2158 }
2159
2160 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2161         meshlink_channel_t *channel = connection->priv;
2162         if(!channel)
2163                 abort();
2164         node_t *n = channel->node;
2165         meshlink_handle_t *mesh = n->mesh;
2166         if(channel->receive_cb)
2167                 channel->receive_cb(mesh, channel, data, len);
2168         return len;
2169 }
2170
2171 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2172         node_t *n = utcp_connection->utcp->priv;
2173         if(!n)
2174                 abort();
2175         meshlink_handle_t *mesh = n->mesh;
2176         if(!mesh->channel_accept_cb)
2177                 return;
2178         meshlink_channel_t *channel = xzalloc(sizeof *channel);
2179         channel->node = n;
2180         channel->c = utcp_connection;
2181         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0))
2182                 utcp_accept(utcp_connection, channel_recv, channel);
2183         else
2184                 free(channel);
2185 }
2186
2187 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2188         node_t *n = utcp->priv;
2189         meshlink_handle_t *mesh = n->mesh;
2190         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? len : -1;
2191 }
2192
2193 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2194         if(!mesh || !channel) {
2195                 meshlink_errno = MESHLINK_EINVAL;
2196                 return;
2197         }
2198
2199         channel->receive_cb = cb;
2200 }
2201
2202 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2203         node_t *n = (node_t *)source;
2204         if(!n->utcp)
2205                 abort();
2206         utcp_recv(n->utcp, data, len);
2207 }
2208
2209 static void channel_poll(struct utcp_connection *connection, size_t len) {
2210         meshlink_channel_t *channel = connection->priv;
2211         if(!channel)
2212                 abort();
2213         node_t *n = channel->node;
2214         meshlink_handle_t *mesh = n->mesh;
2215         if(channel->poll_cb)
2216                 channel->poll_cb(mesh, channel, len);
2217 }
2218
2219 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2220         channel->poll_cb = cb;
2221         utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2222 }
2223
2224 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2225         if(!mesh) {
2226                 meshlink_errno = MESHLINK_EINVAL;
2227                 return;
2228         }
2229
2230         pthread_mutex_lock(&mesh->mesh_mutex);
2231         mesh->channel_accept_cb = cb;
2232         mesh->receive_cb = channel_receive;
2233         for splay_each(node_t, n, mesh->nodes) {
2234                 if(!n->utcp && n != mesh->self) {
2235                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2236                 }
2237         }
2238         pthread_mutex_unlock(&mesh->mesh_mutex);
2239 }
2240
2241 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) {
2242         if(!mesh || !node) {
2243                 meshlink_errno = MESHLINK_EINVAL;
2244                 return NULL;
2245         }
2246
2247         node_t *n = (node_t *)node;
2248         if(!n->utcp) {
2249                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2250                 mesh->receive_cb = channel_receive;
2251                 if(!n->utcp) {
2252                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2253                         return NULL;
2254                 }
2255         }
2256         meshlink_channel_t *channel = xzalloc(sizeof *channel);
2257         channel->node = n;
2258         channel->receive_cb = cb;
2259         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2260         if(!channel->c) {
2261                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2262                 free(channel);
2263                 return NULL;
2264         }
2265         return channel;
2266 }
2267
2268 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) {
2269         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2270 }
2271
2272 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2273         if(!mesh || !channel) {
2274                 meshlink_errno = MESHLINK_EINVAL;
2275                 return;
2276         }
2277
2278         utcp_shutdown(channel->c, direction);
2279 }
2280
2281 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2282         if(!mesh || !channel) {
2283                 meshlink_errno = MESHLINK_EINVAL;
2284                 return;
2285         }
2286
2287         utcp_close(channel->c);
2288         free(channel);
2289 }
2290
2291 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2292         if(!mesh || !channel) {
2293                 meshlink_errno = MESHLINK_EINVAL;
2294                 return -1;
2295         }
2296
2297         if(!len)
2298                 return 0;
2299
2300         if(!data) {
2301                 meshlink_errno = MESHLINK_EINVAL;
2302                 return -1;
2303         }
2304
2305         // TODO: more finegrained locking.
2306         // Ideally we want to put the data into the UTCP connection's send buffer.
2307         // Then, preferrably only if there is room in the receiver window,
2308         // kick the meshlink thread to go send packets.
2309
2310         pthread_mutex_lock(&mesh->mesh_mutex);
2311         ssize_t retval = utcp_send(channel->c, data, len);
2312         pthread_mutex_unlock(&mesh->mesh_mutex);
2313
2314         if(retval < 0)
2315                 meshlink_errno = MESHLINK_ENETWORK;
2316         return retval;
2317 }
2318
2319 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2320         if(!mesh || !channel) {
2321                 meshlink_errno = MESHLINK_EINVAL;
2322                 return -1;
2323         }
2324
2325         return channel->c->flags;
2326 }
2327
2328 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2329         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp)
2330                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2331         if(mesh->node_status_cb)
2332                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2333 }
2334
2335 static void __attribute__((constructor)) meshlink_init(void) {
2336         crypto_init();
2337         unsigned int seed;
2338         randomize(&seed, sizeof seed);
2339         srand(seed);
2340 }
2341
2342 static void __attribute__((destructor)) meshlink_exit(void) {
2343         crypto_exit();
2344 }
2345
2346 /// Device class traits
2347 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX +1] = {
2348         { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2349         { .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
2350         { .min_connects = 3, .max_connects = 3, .edge_weight = 6 },             // DEV_CLASS_PORTABLE
2351         { .min_connects = 1, .max_connects = 1, .edge_weight = 9 },             // DEV_CLASS_UNKNOWN
2352 };