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