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