]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Removed references to HAVE_STRUCT_SOCKADDR_STORAGE.
[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                 return false;
508
509         fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
510         fprintf(fh, "Port = %s\n", mesh->myport);
511
512         fclose(fh);
513
514         sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
515         free(b64key);
516
517         free(mesh->self->name);
518         free(mesh->self->connection->name);
519         mesh->self->name = xstrdup(name);
520         mesh->self->connection->name = name;
521
522         logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
523
524         load_all_nodes(mesh);
525
526         return true;
527 }
528
529 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
530         meshlink_handle_t* mesh = handle;
531         while(len) {
532                 int result = send(mesh->sock, data, len, 0);
533                 if(result == -1 && errno == EINTR)
534                         continue;
535                 else if(result <= 0)
536                         return false;
537                 data += result;
538                 len -= result;
539         }
540         return true;
541 }
542
543 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
544         meshlink_handle_t* mesh = handle;
545         switch(type) {
546                 case SPTPS_HANDSHAKE:
547                         return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
548
549                 case 0:
550                         mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
551                         memcpy(mesh->data + mesh->thedatalen, msg, len);
552                         mesh->thedatalen += len;
553                         mesh->data[mesh->thedatalen] = 0;
554                         break;
555
556                 case 1:
557                         return finalize_join(mesh);
558
559                 case 2:
560                         logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
561                         shutdown(mesh->sock, SHUT_RDWR);
562                         mesh->success = true;
563                         break;
564
565                 default:
566                         return false;
567         }
568
569         return true;
570 }
571
572 static bool recvline(meshlink_handle_t* mesh, size_t len) {
573         char *newline = NULL;
574
575         if(!mesh->sock)
576                 abort();
577
578         while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
579                 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
580                 if(result == -1 && errno == EINTR)
581                         continue;
582                 else if(result <= 0)
583                         return false;
584                 mesh->blen += result;
585         }
586
587         if(newline - mesh->buffer >= len)
588                 return false;
589
590         len = newline - mesh->buffer;
591
592         memcpy(mesh->line, mesh->buffer, len);
593         mesh->line[len] = 0;
594         memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
595         mesh->blen -= len + 1;
596
597         return true;
598 }
599 static bool sendline(int fd, char *format, ...) {
600         static char buffer[4096];
601         char *p = buffer;
602         int blen = 0;
603         va_list ap;
604
605         va_start(ap, format);
606         blen = vsnprintf(buffer, sizeof buffer, format, ap);
607         va_end(ap);
608
609         if(blen < 1 || blen >= sizeof buffer)
610                 return false;
611
612         buffer[blen] = '\n';
613         blen++;
614
615         while(blen) {
616                 int result = send(fd, p, blen, MSG_NOSIGNAL);
617                 if(result == -1 && errno == EINTR)
618                         continue;
619                 else if(result <= 0)
620                         return false;
621                 p += result;
622                 blen -= result;
623         }
624
625         return true;
626 }
627
628 static const char *errstr[] = {
629         [MESHLINK_OK] = "No error",
630         [MESHLINK_EINVAL] = "Invalid argument",
631         [MESHLINK_ENOMEM] = "Out of memory",
632         [MESHLINK_ENOENT] = "No such node",
633         [MESHLINK_EEXIST] = "Node already exists",
634         [MESHLINK_EINTERNAL] = "Internal error",
635         [MESHLINK_ERESOLV] = "Could not resolve hostname",
636         [MESHLINK_ESTORAGE] = "Storage error",
637         [MESHLINK_ENETWORK] = "Network error",
638         [MESHLINK_EPEER] = "Error communicating with peer",
639 };
640
641 const char *meshlink_strerror(meshlink_errno_t err) {
642         if(err < 0 || err >= sizeof errstr / sizeof *errstr)
643                 return "Invalid error code";
644         return errstr[err];
645 }
646
647 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
648         ecdsa_t *key;
649         FILE *f;
650         char pubname[PATH_MAX], privname[PATH_MAX];
651
652         logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
653
654         if(!(key = ecdsa_generate())) {
655                 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
656                 meshlink_errno = MESHLINK_EINTERNAL;
657                 return false;
658         } else
659                 logger(mesh, MESHLINK_DEBUG, "Done.\n");
660
661         snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
662         f = fopen(privname, "w");
663
664         if(!f) {
665                 meshlink_errno = MESHLINK_ESTORAGE;
666                 return false;
667         }
668
669 #ifdef HAVE_FCHMOD
670         fchmod(fileno(f), 0600);
671 #endif
672
673         if(!ecdsa_write_pem_private_key(key, f)) {
674                 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
675                 ecdsa_free(key);
676                 fclose(f);
677                 meshlink_errno = MESHLINK_EINTERNAL;
678                 return false;
679         }
680
681         fclose(f);
682
683         snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
684         f = fopen(pubname, "a");
685
686         if(!f) {
687                 meshlink_errno = MESHLINK_ESTORAGE;
688                 return false;
689         }
690
691         char *pubkey = ecdsa_get_base64_public_key(key);
692         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
693         free(pubkey);
694
695         fclose(f);
696         ecdsa_free(key);
697
698         return true;
699 }
700
701 static bool meshlink_setup(meshlink_handle_t *mesh) {
702         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
703                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
704                 meshlink_errno = MESHLINK_ESTORAGE;
705                 return false;
706         }
707
708         char filename[PATH_MAX];
709         snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
710
711         if(mkdir(filename, 0777) && errno != EEXIST) {
712                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
713                 meshlink_errno = MESHLINK_ESTORAGE;
714                 return false;
715         }
716
717         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
718
719         if(!access(filename, F_OK)) {
720                 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
721                 meshlink_errno = MESHLINK_EEXIST;
722                 return false;
723         }
724
725         FILE *f = fopen(filename, "w");
726         if(!f) {
727                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
728                 meshlink_errno = MESHLINK_ESTORAGE;
729                 return false;
730         }
731
732         fprintf(f, "Name = %s\n", mesh->name);
733         fclose(f);
734
735         if(!ecdsa_keygen(mesh)) {
736                 meshlink_errno = MESHLINK_EINTERNAL;
737                 return false;
738         }
739
740         check_port(mesh);
741
742         return true;
743 }
744
745 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dclass_t dclass) {
746         return meshlink_open_with_size(confbase, name, appname, dclass, sizeof(meshlink_handle_t));
747 }
748
749 meshlink_handle_t *meshlink_open_with_size(const char *confbase, const char *name, const char* appname, dclass_t dclass, size_t size) {
750
751         // Validate arguments provided by the application
752         bool usingname = false;
753         
754         logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
755
756         if(!confbase || !*confbase) {
757                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
758                 meshlink_errno = MESHLINK_EINVAL;
759                 return NULL;
760         }
761
762         if(!appname || !*appname) {
763                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
764                 meshlink_errno = MESHLINK_EINVAL;
765                 return NULL;
766         }
767
768         if(!name || !*name) {
769                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
770                 //return NULL;
771         }
772         else { //check name only if there is a name != NULL
773
774                 if(!check_id(name)) {
775                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
776                         meshlink_errno = MESHLINK_EINVAL;
777                         return NULL;
778                 } else { usingname = true;}
779         }
780
781         meshlink_handle_t *mesh = xzalloc(size);
782         mesh->confbase = xstrdup(confbase);
783         mesh->appname = xstrdup(appname);
784         mesh->dclass = dclass;
785         if (usingname) mesh->name = xstrdup(name);
786
787         // initialize mutex
788         pthread_mutexattr_t attr;
789         pthread_mutexattr_init(&attr);
790         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
791         pthread_mutex_init(&(mesh->mesh_mutex), &attr);
792         
793         mesh->threadstarted = false;
794         event_loop_init(&mesh->loop);
795         mesh->loop.data = mesh;
796
797         // Check whether meshlink.conf already exists
798
799         char filename[PATH_MAX];
800         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
801
802         if(access(filename, R_OK)) {
803                 if(errno == ENOENT) {
804                         // If not, create it
805                         if(!meshlink_setup(mesh)) {
806                                 // meshlink_errno is set by meshlink_setup()
807                                 return NULL;
808                         }
809                 } else {
810                         logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
811                         meshlink_close(mesh);
812                         meshlink_errno = MESHLINK_ESTORAGE;
813                         return NULL;
814                 }
815         }
816
817         // Read the configuration
818
819         init_configuration(&mesh->config);
820
821         if(!read_server_config(mesh)) {
822                 meshlink_close(mesh);
823                 meshlink_errno = MESHLINK_ESTORAGE;
824                 return NULL;
825         };
826
827 #ifdef HAVE_MINGW
828         struct WSAData wsa_state;
829         WSAStartup(MAKEWORD(2, 2), &wsa_state);
830 #endif
831
832         // Setup up everything
833         // TODO: we should not open listening sockets yet
834
835         if(!setup_network(mesh)) {
836                 meshlink_close(mesh);
837                 meshlink_errno = MESHLINK_ENETWORK;
838                 return NULL;
839         }
840
841         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
842         return mesh;
843 }
844
845 static void *meshlink_main_loop(void *arg) {
846         meshlink_handle_t *mesh = arg;
847
848         pthread_mutex_lock(&(mesh->mesh_mutex));
849
850         try_outgoing_connections(mesh);
851
852         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
853         main_loop(mesh);
854         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
855
856         pthread_mutex_unlock(&(mesh->mesh_mutex));
857         return NULL;
858 }
859
860 bool meshlink_start(meshlink_handle_t *mesh) {
861         if(!mesh) {
862                 meshlink_errno = MESHLINK_EINVAL;
863                 return false;
864         }
865         pthread_mutex_lock(&(mesh->mesh_mutex));
866         
867         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
868
869         // TODO: open listening sockets first
870
871         //Check that a valid name is set
872         if(!mesh->name ) {
873                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
874                 meshlink_errno = MESHLINK_EINVAL;
875                 pthread_mutex_unlock(&(mesh->mesh_mutex));
876                 return false;
877         }
878
879         // Start the main thread
880
881         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
882                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
883                 memset(&mesh->thread, 0, sizeof mesh->thread);
884                 meshlink_errno = MESHLINK_EINTERNAL;
885                 pthread_mutex_unlock(&(mesh->mesh_mutex));
886                 return false;
887         }
888
889         mesh->threadstarted=true;
890
891         discovery_start(mesh);
892
893         pthread_mutex_unlock(&(mesh->mesh_mutex));
894         return true;
895 }
896
897 void meshlink_stop(meshlink_handle_t *mesh) {
898         if(!mesh) {
899                 meshlink_errno = MESHLINK_EINVAL;
900                 return;
901         }
902
903         pthread_mutex_lock(&(mesh->mesh_mutex));
904         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
905
906         // Stop discovery
907         discovery_stop(mesh);
908
909         // Shut down a listening socket to signal the main thread to shut down
910
911         listen_socket_t *s = &mesh->listen_socket[0];
912         shutdown(s->tcp.fd, SHUT_RDWR);
913
914         // Wait for the main thread to finish
915         pthread_mutex_unlock(&(mesh->mesh_mutex));
916         pthread_join(mesh->thread, NULL);
917         pthread_mutex_lock(&(mesh->mesh_mutex));
918
919         mesh->threadstarted = false;
920
921         // Fix the socket
922         
923         closesocket(s->tcp.fd);
924         io_del(&mesh->loop, &s->tcp);
925         s->tcp.fd = setup_listen_socket(&s->sa);
926         if(s->tcp.fd < 0)
927                 logger(mesh, MESHLINK_ERROR, "Could not repair listenen socket!");
928         else
929                 io_add(&mesh->loop, &s->tcp, handle_new_meta_connection, s, s->tcp.fd, IO_READ);
930         
931         pthread_mutex_unlock(&(mesh->mesh_mutex));
932 }
933
934 void meshlink_close(meshlink_handle_t *mesh) {
935         if(!mesh || !mesh->confbase) {
936                 meshlink_errno = MESHLINK_EINVAL;
937                 return;
938         }
939
940         // lock is not released after this
941         pthread_mutex_lock(&(mesh->mesh_mutex));
942
943         // Close and free all resources used.
944
945         close_network_connections(mesh);
946
947         logger(mesh, MESHLINK_INFO, "Terminating");
948
949         exit_configuration(&mesh->config);
950         event_loop_exit(&mesh->loop);
951
952 #ifdef HAVE_MINGW
953         if(mesh->confbase)
954                 WSACleanup();
955 #endif
956
957         ecdsa_free(mesh->invitation_key);
958
959         free(mesh->name);
960         free(mesh->appname);
961         free(mesh->confbase);
962         pthread_mutex_destroy(&(mesh->mesh_mutex));
963
964         memset(mesh, 0, sizeof *mesh);
965
966         free(mesh);
967 }
968
969 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
970         if(!mesh) {
971                 meshlink_errno = MESHLINK_EINVAL;
972                 return;
973         }
974
975         pthread_mutex_lock(&(mesh->mesh_mutex));
976         mesh->receive_cb = cb;
977         pthread_mutex_unlock(&(mesh->mesh_mutex));
978 }
979
980 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
981         if(!mesh) {
982                 meshlink_errno = MESHLINK_EINVAL;
983                 return;
984         }
985
986         pthread_mutex_lock(&(mesh->mesh_mutex));
987         mesh->node_status_cb = cb;
988         pthread_mutex_unlock(&(mesh->mesh_mutex));
989 }
990
991 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
992         if(mesh) {
993                 pthread_mutex_lock(&(mesh->mesh_mutex));
994                 mesh->log_cb = cb;
995                 mesh->log_level = cb ? level : 0;
996                 pthread_mutex_unlock(&(mesh->mesh_mutex));
997         } else {
998                 global_log_cb = cb;
999                 global_log_level = cb ? level : 0;
1000         }
1001 }
1002
1003 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1004         if(!mesh || !destination) {
1005                 meshlink_errno = MESHLINK_EINVAL;
1006                 return false;
1007         }
1008
1009         if(!len)
1010                 return true;
1011
1012         if(!data) {
1013                 meshlink_errno = MESHLINK_EINVAL;
1014                 return false;
1015         }
1016
1017         pthread_mutex_lock(&(mesh->mesh_mutex));
1018
1019         //add packet to the queue
1020         outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
1021         packet_in_queue->destination=destination;
1022         packet_in_queue->data=data;
1023         packet_in_queue->len=len;
1024         if(!meshlink_queue_push(&mesh->outpacketqueue, packet_in_queue)) {
1025                 free(packet_in_queue);
1026                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1027                 return false;
1028         }
1029
1030         //notify event loop
1031         signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1032         
1033         pthread_mutex_unlock(&(mesh->mesh_mutex));
1034         return true;
1035 }
1036
1037 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
1038         pthread_mutex_lock(&(mesh->mesh_mutex));
1039         
1040         vpn_packet_t packet;
1041         meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
1042
1043         outpacketqueue_t* p = meshlink_queue_pop(&mesh->outpacketqueue);
1044         if(!p)
1045         {
1046                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1047                 return;
1048         }
1049
1050         if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
1051                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1052                 //log something
1053                 return;
1054         }
1055
1056         packet.probe = false;
1057         memset(hdr, 0, sizeof *hdr);
1058         memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
1059         memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
1060
1061         packet.len = sizeof *hdr + p->len;
1062         memcpy(packet.data + sizeof *hdr, p->data, p->len);
1063
1064         mesh->self->in_packets++;
1065         mesh->self->in_bytes += packet.len;
1066         route(mesh, mesh->self, &packet);
1067         
1068         pthread_mutex_unlock(&(mesh->mesh_mutex));
1069         return ;
1070 }
1071
1072 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1073         if(!mesh || !destination) {
1074                 meshlink_errno = MESHLINK_EINVAL;
1075                 return -1;
1076         }
1077         pthread_mutex_lock(&(mesh->mesh_mutex));
1078
1079         node_t *n = (node_t *)destination;
1080         if(!n->status.reachable) {
1081                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1082                 return 0;
1083         
1084         }
1085         else if(n->mtuprobes > 30 && n->minmtu) {
1086                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1087                 return n->minmtu;
1088         }
1089         else {
1090                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1091                 return MTU;
1092         }
1093 }
1094
1095 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1096         if(!mesh || !node) {
1097                 meshlink_errno = MESHLINK_EINVAL;
1098                 return NULL;
1099         }
1100         pthread_mutex_lock(&(mesh->mesh_mutex));
1101
1102         node_t *n = (node_t *)node;
1103
1104         if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1105                 meshlink_errno = MESHLINK_EINTERNAL;
1106                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1107                 return false;
1108         }
1109
1110         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1111
1112         if(!fingerprint)
1113                 meshlink_errno = MESHLINK_EINTERNAL;
1114
1115         pthread_mutex_unlock(&(mesh->mesh_mutex));
1116         return fingerprint;
1117 }
1118
1119 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1120         if(!mesh || !name) {
1121                 meshlink_errno = MESHLINK_EINVAL;
1122                 return NULL;
1123         }
1124
1125         meshlink_node_t *node = NULL;
1126
1127         pthread_mutex_lock(&(mesh->mesh_mutex));
1128         node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1129         pthread_mutex_unlock(&(mesh->mesh_mutex));
1130         return node;
1131 }
1132
1133 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1134         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1135                 meshlink_errno = MESHLINK_EINVAL;
1136                 return NULL;
1137         }
1138
1139         meshlink_node_t **result;
1140
1141         //lock mesh->nodes
1142         pthread_mutex_lock(&(mesh->mesh_mutex));
1143
1144         *nmemb = mesh->nodes->count;
1145         result = realloc(nodes, *nmemb * sizeof *nodes);
1146
1147         if(result) {
1148                 meshlink_node_t **p = result;
1149                 for splay_each(node_t, n, mesh->nodes)
1150                         *p++ = (meshlink_node_t *)n;
1151         } else {
1152                 *nmemb = 0;
1153                 free(nodes);
1154                 meshlink_errno = MESHLINK_ENOMEM;
1155         }
1156
1157         pthread_mutex_unlock(&(mesh->mesh_mutex));
1158
1159         return result;
1160 }
1161
1162 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1163         if(!mesh || !data || !len || !signature || !siglen) {
1164                 meshlink_errno = MESHLINK_EINVAL;
1165                 return false;
1166         }
1167
1168         if(*siglen < MESHLINK_SIGLEN) {
1169                 meshlink_errno = MESHLINK_EINVAL;
1170                 return false;
1171         }
1172
1173         pthread_mutex_lock(&(mesh->mesh_mutex));
1174
1175         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1176                 meshlink_errno = MESHLINK_EINTERNAL;
1177                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1178                 return false;
1179         }
1180
1181         *siglen = MESHLINK_SIGLEN;
1182         pthread_mutex_unlock(&(mesh->mesh_mutex));
1183         return true;
1184 }
1185
1186 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1187         if(!mesh || !data || !len || !signature) {
1188                 meshlink_errno = MESHLINK_EINVAL;
1189                 return false;
1190         }
1191
1192         if(siglen != MESHLINK_SIGLEN) {
1193                 meshlink_errno = MESHLINK_EINVAL;
1194                 return false;
1195         }
1196
1197         pthread_mutex_lock(&(mesh->mesh_mutex));
1198
1199         bool rval = false;
1200
1201         struct node_t *n = (struct node_t *)source;
1202         node_read_ecdsa_public_key(mesh, n);
1203         if(!n->ecdsa) {
1204                 meshlink_errno = MESHLINK_EINTERNAL;
1205                 rval = false;
1206         } else {
1207                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1208         }
1209         pthread_mutex_unlock(&(mesh->mesh_mutex));
1210         return rval;
1211 }
1212
1213 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1214         char filename[PATH_MAX];
1215         
1216         pthread_mutex_lock(&(mesh->mesh_mutex));
1217
1218         snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1219         if(mkdir(filename, 0700) && errno != EEXIST) {
1220                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1221                 meshlink_errno = MESHLINK_ESTORAGE;
1222                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1223                 return false;
1224         }
1225
1226         // Count the number of valid invitations, clean up old ones
1227         DIR *dir = opendir(filename);
1228         if(!dir) {
1229                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1230                 meshlink_errno = MESHLINK_ESTORAGE;
1231                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1232                 return false;
1233         }
1234
1235         errno = 0;
1236         int count = 0;
1237         struct dirent *ent;
1238         time_t deadline = time(NULL) - 604800; // 1 week in the past
1239
1240         while((ent = readdir(dir))) {
1241                 if(strlen(ent->d_name) != 24)
1242                         continue;
1243                 char invname[PATH_MAX];
1244                 struct stat st;
1245                 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1246                 if(!stat(invname, &st)) {
1247                         if(mesh->invitation_key && deadline < st.st_mtime)
1248                                 count++;
1249                         else
1250                                 unlink(invname);
1251                 } else {
1252                         logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1253                         errno = 0;
1254                 }
1255         }
1256
1257         if(errno) {
1258                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1259                 closedir(dir);
1260                 meshlink_errno = MESHLINK_ESTORAGE;
1261                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1262                 return false;
1263         }
1264
1265         closedir(dir);
1266
1267         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1268
1269         // Remove the key if there are no outstanding invitations.
1270         if(!count) {
1271                 unlink(filename);
1272                 if(mesh->invitation_key) {
1273                         ecdsa_free(mesh->invitation_key);
1274                         mesh->invitation_key = NULL;
1275                 }
1276         }
1277
1278         if(mesh->invitation_key) {
1279                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1280                 return true;
1281         }
1282
1283         // Create a new key if necessary.
1284         FILE *f = fopen(filename, "r");
1285         if(!f) {
1286                 if(errno != ENOENT) {
1287                         logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1288                         meshlink_errno = MESHLINK_ESTORAGE;
1289                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1290                         return false;
1291                 }
1292
1293                 mesh->invitation_key = ecdsa_generate();
1294                 if(!mesh->invitation_key) {
1295                         logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1296                         meshlink_errno = MESHLINK_EINTERNAL;
1297                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1298                         return false;
1299                 }
1300                 f = fopen(filename, "w");
1301                 if(!f) {
1302                         logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1303                         meshlink_errno = MESHLINK_ESTORAGE;
1304                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1305                         return false;
1306                 }
1307                 chmod(filename, 0600);
1308                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1309                 fclose(f);
1310         } else {
1311                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1312                 fclose(f);
1313                 if(!mesh->invitation_key) {
1314                         logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1315                         meshlink_errno = MESHLINK_ESTORAGE;
1316                 }
1317         }
1318
1319         pthread_mutex_unlock(&(mesh->mesh_mutex));
1320         return mesh->invitation_key;
1321 }
1322
1323 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1324         if(!mesh || !address) {
1325                 meshlink_errno = MESHLINK_EINVAL;
1326                 return false;
1327         }
1328         
1329         bool rval = false;
1330
1331         pthread_mutex_lock(&(mesh->mesh_mutex));
1332
1333         for(const char *p = address; *p; p++) {
1334                 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1335                         continue;
1336                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1337                 meshlink_errno = MESHLINK_EINVAL;
1338                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1339                 return false;
1340         }
1341
1342         rval = append_config_file(mesh, mesh->self->name, "Address", address);
1343         pthread_mutex_unlock(&(mesh->mesh_mutex));
1344         return rval;
1345 }
1346
1347 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1348         if(!mesh) {
1349                 meshlink_errno = MESHLINK_EINVAL;
1350                 return NULL;
1351         }
1352         
1353         pthread_mutex_lock(&(mesh->mesh_mutex));
1354
1355         // Check validity of the new node's name
1356         if(!check_id(name)) {
1357                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1358                 meshlink_errno = MESHLINK_EINVAL;
1359                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1360                 return NULL;
1361         }
1362
1363         // Ensure no host configuration file with that name exists
1364         char filename[PATH_MAX];
1365         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1366         if(!access(filename, F_OK)) {
1367                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1368                 meshlink_errno = MESHLINK_EEXIST;
1369                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1370                 return NULL;
1371         }
1372
1373         // Ensure no other nodes know about this name
1374         if(meshlink_get_node(mesh, name)) {
1375                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1376                 meshlink_errno = MESHLINK_EEXIST;
1377                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1378                 return NULL;
1379         }
1380
1381         // Get the local address
1382         char *address = get_my_hostname(mesh);
1383         if(!address) {
1384                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1385                 meshlink_errno = MESHLINK_ERESOLV;
1386                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1387                 return NULL;
1388         }
1389
1390         if(!refresh_invitation_key(mesh)) {
1391                 meshlink_errno = MESHLINK_EINTERNAL;
1392                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1393                 return NULL;
1394         }
1395
1396         char hash[64];
1397
1398         // Create a hash of the key.
1399         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1400         sha512(fingerprint, strlen(fingerprint), hash);
1401         b64encode_urlsafe(hash, hash, 18);
1402
1403         // Create a random cookie for this invitation.
1404         char cookie[25];
1405         randomize(cookie, 18);
1406
1407         // Create a filename that doesn't reveal the cookie itself
1408         char buf[18 + strlen(fingerprint)];
1409         char cookiehash[64];
1410         memcpy(buf, cookie, 18);
1411         memcpy(buf + 18, fingerprint, sizeof buf - 18);
1412         sha512(buf, sizeof buf, cookiehash);
1413         b64encode_urlsafe(cookiehash, cookiehash, 18);
1414
1415         b64encode_urlsafe(cookie, cookie, 18);
1416
1417         free(fingerprint);
1418
1419         // Create a file containing the details of the invitation.
1420         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1421         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1422         if(!ifd) {
1423                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1424                 meshlink_errno = MESHLINK_ESTORAGE;
1425                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1426                 return NULL;
1427         }
1428         FILE *f = fdopen(ifd, "w");
1429         if(!f)
1430                 abort();
1431
1432         // Fill in the details.
1433         fprintf(f, "Name = %s\n", name);
1434         //if(netname)
1435         //      fprintf(f, "NetName = %s\n", netname);
1436         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1437
1438         // Copy Broadcast and Mode
1439         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1440         FILE *tc = fopen(filename,  "r");
1441         if(tc) {
1442                 char buf[1024];
1443                 while(fgets(buf, sizeof buf, tc)) {
1444                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1445                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1446                                 fputs(buf, f);
1447                                 // Make sure there is a newline character.
1448                                 if(!strchr(buf, '\n'))
1449                                         fputc('\n', f);
1450                         }
1451                 }
1452                 fclose(tc);
1453         } else {
1454                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1455                 meshlink_errno = MESHLINK_ESTORAGE;
1456                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1457                 return NULL;
1458         }
1459
1460         fprintf(f, "#---------------------------------------------------------------#\n");
1461         fprintf(f, "Name = %s\n", mesh->self->name);
1462
1463         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1464         fcopy(f, filename);
1465         fclose(f);
1466
1467         // Create an URL from the local address, key hash and cookie
1468         char *url;
1469         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1470         free(address);
1471
1472         pthread_mutex_unlock(&(mesh->mesh_mutex));
1473         return url;
1474 }
1475
1476 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1477         if(!mesh || !invitation) {
1478                 meshlink_errno = MESHLINK_EINVAL;
1479                 return false;
1480         }
1481         
1482         pthread_mutex_lock(&(mesh->mesh_mutex));
1483
1484         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1485         char copy[strlen(invitation) + 1];
1486         strcpy(copy, invitation);
1487
1488         // Split the invitation URL into hostname, port, key hash and cookie.
1489
1490         char *slash = strchr(copy, '/');
1491         if(!slash)
1492                 goto invalid;
1493
1494         *slash++ = 0;
1495
1496         if(strlen(slash) != 48)
1497                 goto invalid;
1498
1499         char *address = copy;
1500         char *port = NULL;
1501         if(*address == '[') {
1502                 address++;
1503                 char *bracket = strchr(address, ']');
1504                 if(!bracket)
1505                         goto invalid;
1506                 *bracket = 0;
1507                 if(bracket[1] == ':')
1508                         port = bracket + 2;
1509         } else {
1510                 port = strchr(address, ':');
1511                 if(port)
1512                         *port++ = 0;
1513         }
1514
1515         if(!port)
1516                 goto invalid;
1517
1518         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1519                 goto invalid;
1520
1521         // Generate a throw-away key for the invitation.
1522         ecdsa_t *key = ecdsa_generate();
1523         if(!key) {
1524                 meshlink_errno = MESHLINK_EINTERNAL;
1525                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1526                 return false;
1527         }
1528
1529         char *b64key = ecdsa_get_base64_public_key(key);
1530
1531         //Before doing meshlink_join make sure we are not connected to another mesh
1532         if ( mesh->threadstarted ){
1533                 goto invalid;
1534         }
1535
1536         // Connect to the meshlink daemon mentioned in the URL.
1537         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1538         if(!ai) {
1539                 meshlink_errno = MESHLINK_ERESOLV;
1540                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1541                 return false;
1542         }
1543
1544         mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1545         if(mesh->sock <= 0) {
1546                 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1547                 freeaddrinfo(ai);
1548                 meshlink_errno = MESHLINK_ENETWORK;
1549                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1550                 return false;
1551         }
1552
1553         if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1554                 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1555                 closesocket(mesh->sock);
1556                 freeaddrinfo(ai);
1557                 meshlink_errno = MESHLINK_ENETWORK;
1558                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1559                 return false;
1560         }
1561
1562         freeaddrinfo(ai);
1563
1564         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1565
1566         // Tell him we have an invitation, and give him our throw-away key.
1567
1568         mesh->blen = 0;
1569
1570         if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1571                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1572                 closesocket(mesh->sock);
1573                 meshlink_errno = MESHLINK_ENETWORK;
1574                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1575                 return false;
1576         }
1577
1578         free(b64key);
1579
1580         char hisname[4096] = "";
1581         int code, hismajor, hisminor = 0;
1582
1583         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) {
1584                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1585                 closesocket(mesh->sock);
1586                 meshlink_errno = MESHLINK_ENETWORK;
1587                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1588                 return false;
1589         }
1590
1591         // Check if the hash of the key he gave us matches the hash in the URL.
1592         char *fingerprint = mesh->line + 2;
1593         char hishash[64];
1594         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1595                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1596                 meshlink_errno = MESHLINK_EINTERNAL;
1597                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1598                 return false;
1599         }
1600         if(memcmp(hishash, mesh->hash, 18)) {
1601                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1602                 meshlink_errno = MESHLINK_EPEER;
1603                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1604                 return false;
1605
1606         }
1607
1608         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1609         if(!hiskey) {
1610                 meshlink_errno = MESHLINK_EINTERNAL;
1611                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1612                 return false;
1613         }
1614
1615         // Start an SPTPS session
1616         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1617                 meshlink_errno = MESHLINK_EINTERNAL;
1618                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1619                 return false;
1620         }
1621
1622         // Feed rest of input buffer to SPTPS
1623         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1624                 meshlink_errno = MESHLINK_EPEER;
1625                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1626                 return false;
1627         }
1628
1629         int len;
1630
1631         while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1632                 if(len < 0) {
1633                         if(errno == EINTR)
1634                                 continue;
1635                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1636                         meshlink_errno = MESHLINK_ENETWORK;
1637                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1638                         return false;
1639                 }
1640
1641                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1642                         meshlink_errno = MESHLINK_EPEER;
1643                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1644                         return false;
1645                 }
1646         }
1647
1648         sptps_stop(&mesh->sptps);
1649         ecdsa_free(hiskey);
1650         ecdsa_free(key);
1651         closesocket(mesh->sock);
1652
1653         if(!mesh->success) {
1654                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1655                 meshlink_errno = MESHLINK_EPEER;
1656                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1657                 return false;
1658         }
1659
1660         pthread_mutex_unlock(&(mesh->mesh_mutex));
1661         return true;
1662
1663 invalid:
1664         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1665         meshlink_errno = MESHLINK_EINVAL;
1666         pthread_mutex_unlock(&(mesh->mesh_mutex));
1667         return false;
1668 }
1669
1670 char *meshlink_export(meshlink_handle_t *mesh) {
1671         if(!mesh) {
1672                 meshlink_errno = MESHLINK_EINVAL;
1673                 return NULL;
1674         }
1675
1676         pthread_mutex_lock(&(mesh->mesh_mutex));
1677         
1678         char filename[PATH_MAX];
1679         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1680         FILE *f = fopen(filename, "r");
1681         if(!f) {
1682                 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1683                 meshlink_errno = MESHLINK_ESTORAGE;
1684                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1685                 return NULL;
1686         }
1687
1688         fseek(f, 0, SEEK_END);
1689         int fsize = ftell(f);
1690         rewind(f);
1691
1692         size_t len = fsize + 9 + strlen(mesh->self->name);
1693         char *buf = xmalloc(len);
1694         snprintf(buf, len, "Name = %s\n", mesh->self->name);
1695         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1696                 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1697                 fclose(f);
1698                 meshlink_errno = MESHLINK_ESTORAGE;
1699                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1700                 return NULL;
1701         }
1702
1703         fclose(f);
1704         buf[len - 1] = 0;
1705         
1706         pthread_mutex_lock(&(mesh->mesh_mutex));
1707         return buf;
1708 }
1709
1710 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1711         if(!mesh || !data) {
1712                 meshlink_errno = MESHLINK_EINVAL;
1713                 return false;
1714         }
1715         
1716         pthread_mutex_lock(&(mesh->mesh_mutex));
1717
1718         if(strncmp(data, "Name = ", 7)) {
1719                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1720                 meshlink_errno = MESHLINK_EPEER;
1721                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1722                 return false;
1723         }
1724
1725         char *end = strchr(data + 7, '\n');
1726         if(!end) {
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         int len = end - (data + 7);
1734         char name[len + 1];
1735         memcpy(name, data + 7, len);
1736         name[len] = 0;
1737         if(!check_id(name)) {
1738                 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1739                 meshlink_errno = MESHLINK_EPEER;
1740                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1741                 return false;
1742         }
1743
1744         char filename[PATH_MAX];
1745         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1746         if(!access(filename, F_OK)) {
1747                 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1748                 meshlink_errno = MESHLINK_EEXIST;
1749                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1750                 return false;
1751         }
1752
1753         if(errno != ENOENT) {
1754                 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1755                 meshlink_errno = MESHLINK_ESTORAGE;
1756                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1757                 return false;
1758         }
1759
1760         FILE *f = fopen(filename, "w");
1761         if(!f) {
1762                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1763                 meshlink_errno = MESHLINK_ESTORAGE;
1764                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1765                 return false;
1766         }
1767
1768         fwrite(end + 1, strlen(end + 1), 1, f);
1769         fclose(f);
1770
1771         load_all_nodes(mesh);
1772
1773         pthread_mutex_unlock(&(mesh->mesh_mutex));
1774         return true;
1775 }
1776
1777 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1778         if(!mesh || !node) {
1779                 meshlink_errno = MESHLINK_EINVAL;
1780                 return;
1781         }
1782
1783         pthread_mutex_lock(&(mesh->mesh_mutex));
1784         
1785         node_t *n;
1786         n = (node_t*)node;
1787         n->status.blacklisted=true;
1788         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n",node->name);
1789
1790         //Make blacklisting persistent in the config file
1791         append_config_file(mesh, n->name, "blacklisted", "yes");
1792
1793         pthread_mutex_unlock(&(mesh->mesh_mutex));
1794         return;
1795 }
1796
1797 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1798         if(!mesh || !node) {
1799                 meshlink_errno = MESHLINK_EINVAL;
1800                 return;
1801         }
1802
1803         pthread_mutex_lock(&(mesh->mesh_mutex));
1804         
1805         node_t *n = (node_t *)node;
1806         n->status.blacklisted = false;
1807
1808         //TODO: remove blacklisted = yes from the config file
1809
1810         pthread_mutex_unlock(&(mesh->mesh_mutex));
1811         return;
1812 }
1813
1814 /* Hint that a hostname may be found at an address
1815  * See header file for detailed comment.
1816  */
1817 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
1818         if(!mesh || !node || !addr)
1819                 return;
1820         
1821         pthread_mutex_lock(&(mesh->mesh_mutex));
1822         
1823         char *host = NULL, *port = NULL, *str = NULL;
1824         sockaddr2str((const sockaddr_t *)addr, &host, &port);
1825
1826         if(host && port) {
1827                 xasprintf(&str, "%s %s", host, port);
1828                 append_config_file(mesh, node->name, "Address", str);
1829         }
1830
1831         free(str);
1832         free(host);
1833         free(port);
1834
1835         pthread_mutex_unlock(&(mesh->mesh_mutex));
1836         // @TODO do we want to fire off a connection attempt right away?
1837 }
1838
1839 /* Return an array of edges in the current network graph.
1840  * Data captures the current state and will not be updated.
1841  * Caller must deallocate data when done.
1842  */
1843 meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
1844         if(!mesh || !nmemb || (*nmemb && !edges)) {
1845                 meshlink_errno = MESHLINK_EINVAL;
1846                 return NULL;
1847         }
1848
1849         pthread_mutex_lock(&(mesh->mesh_mutex));
1850         
1851         meshlink_edge_t **result = NULL;
1852         meshlink_edge_t *copy = NULL;
1853         int result_size = 0;
1854
1855         result_size = mesh->edges->count;
1856
1857         // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
1858         if(result_size > *nmemb) {
1859                 result = realloc(edges, result_size * sizeof (meshlink_edge_t*));
1860         } else {
1861                 result = edges;
1862         }
1863
1864         if(result) {
1865                 meshlink_edge_t **p = result;
1866                 int n = 0;
1867                 for splay_each(edge_t, e, mesh->edges) {
1868                         // skip edges that do not represent a two-directional connection
1869                         if((!e->reverse) || (e->reverse->to != e->from)) {
1870                                 result_size--;
1871                                 continue;
1872                         }
1873                         n++;
1874                         // the first *nmemb members of result can be re-used
1875                         if(n > *nmemb) {
1876                                 copy = xzalloc(sizeof *copy);
1877                         }
1878                         else {
1879                                 copy = *p;
1880                         }
1881                         copy->from = (meshlink_node_t*)e->from;
1882                         copy->to = (meshlink_node_t*)e->to;
1883                         copy->address = e->address.storage;
1884                         copy->options = e->options;
1885                         copy->weight = e->weight;
1886                         *p++ = copy;
1887                 }
1888                 // shrink result to the actual amount of memory used
1889                 for(int i = *nmemb; i > result_size; i--) {
1890                         free(result[i - 1]);
1891                 }
1892                 result = realloc(result, result_size * sizeof (meshlink_edge_t*));
1893                 *nmemb = result_size;
1894         } else {
1895                 *nmemb = 0;
1896                 free(result);
1897                 meshlink_errno = MESHLINK_ENOMEM;
1898         }
1899
1900         pthread_mutex_unlock(&(mesh->mesh_mutex));
1901
1902         return result;
1903 }
1904
1905 static void __attribute__((constructor)) meshlink_init(void) {
1906         crypto_init();
1907 }
1908
1909 static void __attribute__((destructor)) meshlink_exit(void) {
1910         crypto_exit();
1911 }
1912
1913 int weight_from_dclass(dclass_t dclass)
1914 {
1915         switch(dclass)
1916         {
1917         case BACKBONE:
1918                 return 1;
1919
1920         case STATIONARY:
1921                 return 3;
1922
1923         case PORTABLE:
1924                 return 6;
1925         }
1926
1927         return 9;
1928 }