]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
class based connect behaviour
[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         if(!confbase || !*confbase) {
755                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
756                 meshlink_errno = MESHLINK_EINVAL;
757                 return NULL;
758         }
759
760         if(!appname || !*appname) {
761                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
762                 meshlink_errno = MESHLINK_EINVAL;
763                 return NULL;
764         }
765
766         if(!name || !*name) {
767                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
768                 //return NULL;
769         }
770         else { //check name only if there is a name != NULL
771
772                 if(!check_id(name)) {
773                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
774                         meshlink_errno = MESHLINK_EINVAL;
775                         return NULL;
776                 } else { usingname = true;}
777         }
778
779         meshlink_handle_t *mesh = xzalloc(size);
780         mesh->confbase = xstrdup(confbase);
781         mesh->appname = xstrdup(appname);
782         mesh->dclass = dclass;
783         if (usingname) mesh->name = xstrdup(name);
784         pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
785         mesh->threadstarted = false;
786         event_loop_init(&mesh->loop);
787         mesh->loop.data = mesh;
788
789         // Check whether meshlink.conf already exists
790
791         char filename[PATH_MAX];
792         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
793
794         if(access(filename, R_OK)) {
795                 if(errno == ENOENT) {
796                         // If not, create it
797                         if(!meshlink_setup(mesh)) {
798                                 // meshlink_errno is set by meshlink_setup()
799                                 return NULL;
800                         }
801                 } else {
802                         logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
803                         meshlink_close(mesh);
804                         meshlink_errno = MESHLINK_ESTORAGE;
805                         return NULL;
806                 }
807         }
808
809         // Read the configuration
810
811         init_configuration(&mesh->config);
812
813         if(!read_server_config(mesh)) {
814                 meshlink_close(mesh);
815                 meshlink_errno = MESHLINK_ESTORAGE;
816                 return NULL;
817         };
818
819 #ifdef HAVE_MINGW
820         struct WSAData wsa_state;
821         WSAStartup(MAKEWORD(2, 2), &wsa_state);
822 #endif
823
824         // Setup up everything
825         // TODO: we should not open listening sockets yet
826
827         if(!setup_network(mesh)) {
828                 meshlink_close(mesh);
829                 meshlink_errno = MESHLINK_ENETWORK;
830                 return NULL;
831         }
832
833         return mesh;
834 }
835
836 static void *meshlink_main_loop(void *arg) {
837         meshlink_handle_t *mesh = arg;
838
839         try_outgoing_connections(mesh);
840
841         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
842         main_loop(mesh);
843         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
844
845         return NULL;
846 }
847
848 bool meshlink_start(meshlink_handle_t *mesh) {
849
850         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
851
852         if(!mesh) {
853                 meshlink_errno = MESHLINK_EINVAL;
854                 return false;
855         }
856
857         // TODO: open listening sockets first
858
859         //Check that a valid name is set
860         if(!mesh->name ) {
861                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
862                 meshlink_errno = MESHLINK_EINVAL;
863                 return false;
864         }
865
866         // Start the main thread
867
868         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
869                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
870                 memset(&mesh->thread, 0, sizeof mesh->thread);
871                 meshlink_errno = MESHLINK_EINTERNAL;
872                 return false;
873         }
874
875         mesh->threadstarted=true;
876
877         discovery_start(mesh);
878
879         return true;
880 }
881
882 void meshlink_stop(meshlink_handle_t *mesh) {
883
884         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
885         
886         if(!mesh) {
887                 meshlink_errno = MESHLINK_EINVAL;
888                 return;
889         }
890
891         // Stop discovery
892         discovery_stop(mesh);
893
894         // Shut down a listening socket to signal the main thread to shut down
895
896         listen_socket_t *s = &mesh->listen_socket[0];
897         shutdown(s->tcp.fd, SHUT_RDWR);
898
899         // Wait for the main thread to finish
900
901         pthread_join(mesh->thread, NULL);
902         mesh->threadstarted = false;
903
904         // Fix the socket
905         
906         closesocket(s->tcp.fd);
907         io_del(&mesh->loop, &s->tcp);
908         s->tcp.fd = setup_listen_socket(&s->sa);
909         if(s->tcp.fd < 0)
910                 logger(mesh, MESHLINK_ERROR, "Could not repair listenen socket!");
911         else
912                 io_add(&mesh->loop, &s->tcp, handle_new_meta_connection, s, s->tcp.fd, IO_READ);
913 }
914
915 void meshlink_close(meshlink_handle_t *mesh) {
916         if(!mesh || !mesh->confbase) {
917                 meshlink_errno = MESHLINK_EINVAL;
918                 return;
919         }
920
921         // Close and free all resources used.
922
923         close_network_connections(mesh);
924
925         logger(mesh, MESHLINK_INFO, "Terminating");
926
927         exit_configuration(&mesh->config);
928         event_loop_exit(&mesh->loop);
929
930 #ifdef HAVE_MINGW
931         if(mesh->confbase)
932                 WSACleanup();
933 #endif
934
935         ecdsa_free(mesh->invitation_key);
936
937         free(mesh->name);
938         free(mesh->appname);
939         free(mesh->confbase);
940
941         memset(mesh, 0, sizeof *mesh);
942
943         free(mesh);
944 }
945
946 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
947         if(!mesh) {
948                 meshlink_errno = MESHLINK_EINVAL;
949                 return;
950         }
951
952         mesh->receive_cb = cb;
953 }
954
955 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
956         if(!mesh) {
957                 meshlink_errno = MESHLINK_EINVAL;
958                 return;
959         }
960
961         mesh->node_status_cb = cb;
962 }
963
964 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
965         if(mesh) {
966                 mesh->log_cb = cb;
967                 mesh->log_level = cb ? level : 0;
968         } else {
969                 global_log_cb = cb;
970                 global_log_level = cb ? level : 0;
971         }
972 }
973
974 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
975         if(!mesh || !destination) {
976                 meshlink_errno = MESHLINK_EINVAL;
977                 return false;
978         }
979
980         if(!len)
981                 return true;
982
983         if(!data) {
984                 meshlink_errno = MESHLINK_EINVAL;
985                 return false;
986         }
987
988         //add packet to the queue
989         outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
990         packet_in_queue->destination=destination;
991         packet_in_queue->data=data;
992         packet_in_queue->len=len;
993         if(!meshlink_queue_push(&mesh->outpacketqueue, packet_in_queue)) {
994                 free(packet_in_queue);
995                 return false;
996         }
997
998         //notify event loop
999         signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1000         return true;
1001 }
1002
1003 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
1004         vpn_packet_t packet;
1005         meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
1006
1007         outpacketqueue_t* p = meshlink_queue_pop(&mesh->outpacketqueue);
1008         if(!p)
1009                 return;
1010
1011         if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
1012                 //log something
1013                 return ;
1014         }
1015
1016         packet.probe = false;
1017         memset(hdr, 0, sizeof *hdr);
1018         memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
1019         memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
1020
1021         packet.len = sizeof *hdr + p->len;
1022         memcpy(packet.data + sizeof *hdr, p->data, p->len);
1023
1024         mesh->self->in_packets++;
1025         mesh->self->in_bytes += packet.len;
1026         route(mesh, mesh->self, &packet);
1027         return ;
1028 }
1029
1030 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1031         if(!mesh || !destination) {
1032                 meshlink_errno = MESHLINK_EINVAL;
1033                 return -1;
1034         }
1035
1036         node_t *n = (node_t *)destination;
1037         if(!n->status.reachable)
1038                 return 0;
1039         else if(n->mtuprobes > 30 && n->minmtu)
1040                 return n->minmtu;
1041         else
1042                 return MTU;
1043 }
1044
1045 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1046         if(!mesh || !node) {
1047                 meshlink_errno = MESHLINK_EINVAL;
1048                 return NULL;
1049         }
1050
1051         node_t *n = (node_t *)node;
1052
1053         if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1054                 meshlink_errno = MESHLINK_EINTERNAL;
1055                 return false;
1056         }
1057
1058         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1059
1060         if(!fingerprint)
1061                 meshlink_errno = MESHLINK_EINTERNAL;
1062
1063         return fingerprint;
1064 }
1065
1066 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1067         if(!mesh || !name) {
1068                 meshlink_errno = MESHLINK_EINVAL;
1069                 return NULL;
1070         }
1071
1072         return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1073 }
1074
1075 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1076         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1077                 meshlink_errno = MESHLINK_EINVAL;
1078                 return NULL;
1079         }
1080
1081         meshlink_node_t **result;
1082
1083         //lock mesh->nodes
1084         pthread_mutex_lock(&(mesh->nodes_mutex));
1085
1086         *nmemb = mesh->nodes->count;
1087         result = realloc(nodes, *nmemb * sizeof *nodes);
1088
1089         if(result) {
1090                 meshlink_node_t **p = result;
1091                 for splay_each(node_t, n, mesh->nodes)
1092                         *p++ = (meshlink_node_t *)n;
1093         } else {
1094                 *nmemb = 0;
1095                 free(nodes);
1096                 meshlink_errno = MESHLINK_ENOMEM;
1097         }
1098
1099         pthread_mutex_unlock(&(mesh->nodes_mutex));
1100
1101         return result;
1102 }
1103
1104 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1105         if(!mesh || !data || !len || !signature || !siglen) {
1106                 meshlink_errno = MESHLINK_EINVAL;
1107                 return false;
1108         }
1109
1110         if(*siglen < MESHLINK_SIGLEN) {
1111                 meshlink_errno = MESHLINK_EINVAL;
1112                 return false;
1113         }
1114
1115         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1116                 meshlink_errno = MESHLINK_EINTERNAL;
1117                 return false;
1118         }
1119
1120         *siglen = MESHLINK_SIGLEN;
1121         return true;
1122 }
1123
1124 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1125         if(!mesh || !data || !len || !signature) {
1126                 meshlink_errno = MESHLINK_EINVAL;
1127                 return false;
1128         }
1129
1130         if(siglen != MESHLINK_SIGLEN) {
1131                 meshlink_errno = MESHLINK_EINVAL;
1132                 return false;
1133         }
1134
1135         struct node_t *n = (struct node_t *)source;
1136         node_read_ecdsa_public_key(mesh, n);
1137         if(!n->ecdsa) {
1138                 meshlink_errno = MESHLINK_EINTERNAL;
1139                 return false;
1140         }
1141
1142         return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1143 }
1144
1145 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1146         char filename[PATH_MAX];
1147
1148         snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1149         if(mkdir(filename, 0700) && errno != EEXIST) {
1150                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1151                 meshlink_errno = MESHLINK_ESTORAGE;
1152                 return false;
1153         }
1154
1155         // Count the number of valid invitations, clean up old ones
1156         DIR *dir = opendir(filename);
1157         if(!dir) {
1158                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1159                 meshlink_errno = MESHLINK_ESTORAGE;
1160                 return false;
1161         }
1162
1163         errno = 0;
1164         int count = 0;
1165         struct dirent *ent;
1166         time_t deadline = time(NULL) - 604800; // 1 week in the past
1167
1168         while((ent = readdir(dir))) {
1169                 if(strlen(ent->d_name) != 24)
1170                         continue;
1171                 char invname[PATH_MAX];
1172                 struct stat st;
1173                 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1174                 if(!stat(invname, &st)) {
1175                         if(mesh->invitation_key && deadline < st.st_mtime)
1176                                 count++;
1177                         else
1178                                 unlink(invname);
1179                 } else {
1180                         logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1181                         errno = 0;
1182                 }
1183         }
1184
1185         if(errno) {
1186                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1187                 closedir(dir);
1188                 meshlink_errno = MESHLINK_ESTORAGE;
1189                 return false;
1190         }
1191
1192         closedir(dir);
1193
1194         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1195
1196         // Remove the key if there are no outstanding invitations.
1197         if(!count) {
1198                 unlink(filename);
1199                 if(mesh->invitation_key) {
1200                         ecdsa_free(mesh->invitation_key);
1201                         mesh->invitation_key = NULL;
1202                 }
1203         }
1204
1205         if(mesh->invitation_key)
1206                 return true;
1207
1208         // Create a new key if necessary.
1209         FILE *f = fopen(filename, "r");
1210         if(!f) {
1211                 if(errno != ENOENT) {
1212                         logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1213                         meshlink_errno = MESHLINK_ESTORAGE;
1214                         return false;
1215                 }
1216
1217                 mesh->invitation_key = ecdsa_generate();
1218                 if(!mesh->invitation_key) {
1219                         logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1220                         meshlink_errno = MESHLINK_EINTERNAL;
1221                         return false;
1222                 }
1223                 f = fopen(filename, "w");
1224                 if(!f) {
1225                         logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1226                         meshlink_errno = MESHLINK_ESTORAGE;
1227                         return false;
1228                 }
1229                 chmod(filename, 0600);
1230                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1231                 fclose(f);
1232         } else {
1233                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1234                 fclose(f);
1235                 if(!mesh->invitation_key) {
1236                         logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1237                         meshlink_errno = MESHLINK_ESTORAGE;
1238                 }
1239         }
1240
1241         return mesh->invitation_key;
1242 }
1243
1244 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1245         if(!mesh || !address) {
1246                 meshlink_errno = MESHLINK_EINVAL;
1247                 return false;
1248         }
1249
1250         for(const char *p = address; *p; p++) {
1251                 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1252                         continue;
1253                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1254                 meshlink_errno = MESHLINK_EINVAL;
1255                 return false;
1256         }
1257
1258         return append_config_file(mesh, mesh->self->name, "Address", address);
1259 }
1260
1261 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1262         if(!mesh) {
1263                 meshlink_errno = MESHLINK_EINVAL;
1264                 return NULL;
1265         }
1266
1267         // Check validity of the new node's name
1268         if(!check_id(name)) {
1269                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1270                 meshlink_errno = MESHLINK_EINVAL;
1271                 return NULL;
1272         }
1273
1274         // Ensure no host configuration file with that name exists
1275         char filename[PATH_MAX];
1276         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1277         if(!access(filename, F_OK)) {
1278                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1279                 meshlink_errno = MESHLINK_EEXIST;
1280                 return NULL;
1281         }
1282
1283         // Ensure no other nodes know about this name
1284         if(meshlink_get_node(mesh, name)) {
1285                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1286                 meshlink_errno = MESHLINK_EEXIST;
1287                 return NULL;
1288         }
1289
1290         // Get the local address
1291         char *address = get_my_hostname(mesh);
1292         if(!address) {
1293                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1294                 meshlink_errno = MESHLINK_ERESOLV;
1295                 return NULL;
1296         }
1297
1298         if(!refresh_invitation_key(mesh)) {
1299                 meshlink_errno = MESHLINK_EINTERNAL;
1300                 return NULL;
1301         }
1302
1303         char hash[64];
1304
1305         // Create a hash of the key.
1306         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1307         sha512(fingerprint, strlen(fingerprint), hash);
1308         b64encode_urlsafe(hash, hash, 18);
1309
1310         // Create a random cookie for this invitation.
1311         char cookie[25];
1312         randomize(cookie, 18);
1313
1314         // Create a filename that doesn't reveal the cookie itself
1315         char buf[18 + strlen(fingerprint)];
1316         char cookiehash[64];
1317         memcpy(buf, cookie, 18);
1318         memcpy(buf + 18, fingerprint, sizeof buf - 18);
1319         sha512(buf, sizeof buf, cookiehash);
1320         b64encode_urlsafe(cookiehash, cookiehash, 18);
1321
1322         b64encode_urlsafe(cookie, cookie, 18);
1323
1324         free(fingerprint);
1325
1326         // Create a file containing the details of the invitation.
1327         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1328         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1329         if(!ifd) {
1330                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1331                 meshlink_errno = MESHLINK_ESTORAGE;
1332                 return NULL;
1333         }
1334         FILE *f = fdopen(ifd, "w");
1335         if(!f)
1336                 abort();
1337
1338         // Fill in the details.
1339         fprintf(f, "Name = %s\n", name);
1340         //if(netname)
1341         //      fprintf(f, "NetName = %s\n", netname);
1342         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1343
1344         // Copy Broadcast and Mode
1345         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1346         FILE *tc = fopen(filename,  "r");
1347         if(tc) {
1348                 char buf[1024];
1349                 while(fgets(buf, sizeof buf, tc)) {
1350                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1351                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1352                                 fputs(buf, f);
1353                                 // Make sure there is a newline character.
1354                                 if(!strchr(buf, '\n'))
1355                                         fputc('\n', f);
1356                         }
1357                 }
1358                 fclose(tc);
1359         } else {
1360                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1361                 meshlink_errno = MESHLINK_ESTORAGE;
1362                 return NULL;
1363         }
1364
1365         fprintf(f, "#---------------------------------------------------------------#\n");
1366         fprintf(f, "Name = %s\n", mesh->self->name);
1367
1368         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1369         fcopy(f, filename);
1370         fclose(f);
1371
1372         // Create an URL from the local address, key hash and cookie
1373         char *url;
1374         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1375         free(address);
1376
1377         return url;
1378 }
1379
1380 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1381         if(!mesh || !invitation) {
1382                 meshlink_errno = MESHLINK_EINVAL;
1383                 return false;
1384         }
1385
1386         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1387         char copy[strlen(invitation) + 1];
1388         strcpy(copy, invitation);
1389
1390         // Split the invitation URL into hostname, port, key hash and cookie.
1391
1392         char *slash = strchr(copy, '/');
1393         if(!slash)
1394                 goto invalid;
1395
1396         *slash++ = 0;
1397
1398         if(strlen(slash) != 48)
1399                 goto invalid;
1400
1401         char *address = copy;
1402         char *port = NULL;
1403         if(*address == '[') {
1404                 address++;
1405                 char *bracket = strchr(address, ']');
1406                 if(!bracket)
1407                         goto invalid;
1408                 *bracket = 0;
1409                 if(bracket[1] == ':')
1410                         port = bracket + 2;
1411         } else {
1412                 port = strchr(address, ':');
1413                 if(port)
1414                         *port++ = 0;
1415         }
1416
1417         if(!port)
1418                 goto invalid;
1419
1420         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1421                 goto invalid;
1422
1423         // Generate a throw-away key for the invitation.
1424         ecdsa_t *key = ecdsa_generate();
1425         if(!key) {
1426                 meshlink_errno = MESHLINK_EINTERNAL;
1427                 return false;
1428         }
1429
1430         char *b64key = ecdsa_get_base64_public_key(key);
1431
1432         //Before doing meshlink_join make sure we are not connected to another mesh
1433         if ( mesh->threadstarted ){
1434                 goto invalid;
1435         }
1436
1437         // Connect to the meshlink daemon mentioned in the URL.
1438         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1439         if(!ai) {
1440                 meshlink_errno = MESHLINK_ERESOLV;
1441                 return false;
1442         }
1443
1444         mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1445         if(mesh->sock <= 0) {
1446                 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1447                 freeaddrinfo(ai);
1448                 meshlink_errno = MESHLINK_ENETWORK;
1449                 return false;
1450         }
1451
1452         if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1453                 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1454                 closesocket(mesh->sock);
1455                 freeaddrinfo(ai);
1456                 meshlink_errno = MESHLINK_ENETWORK;
1457                 return false;
1458         }
1459
1460         freeaddrinfo(ai);
1461
1462         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1463
1464         // Tell him we have an invitation, and give him our throw-away key.
1465
1466         mesh->blen = 0;
1467
1468         if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1469                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1470                 closesocket(mesh->sock);
1471                 meshlink_errno = MESHLINK_ENETWORK;
1472                 return false;
1473         }
1474
1475         free(b64key);
1476
1477         char hisname[4096] = "";
1478         int code, hismajor, hisminor = 0;
1479
1480         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) {
1481                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1482                 closesocket(mesh->sock);
1483                 meshlink_errno = MESHLINK_ENETWORK;
1484                 return false;
1485         }
1486
1487         // Check if the hash of the key he gave us matches the hash in the URL.
1488         char *fingerprint = mesh->line + 2;
1489         char hishash[64];
1490         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1491                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1492                 meshlink_errno = MESHLINK_EINTERNAL;
1493                 return false;
1494         }
1495         if(memcmp(hishash, mesh->hash, 18)) {
1496                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1497                 meshlink_errno = MESHLINK_EPEER;
1498                 return false;
1499
1500         }
1501
1502         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1503         if(!hiskey) {
1504                 meshlink_errno = MESHLINK_EINTERNAL;
1505                 return false;
1506         }
1507
1508         // Start an SPTPS session
1509         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1510                 meshlink_errno = MESHLINK_EINTERNAL;
1511                 return false;
1512         }
1513
1514         // Feed rest of input buffer to SPTPS
1515         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1516                 meshlink_errno = MESHLINK_EPEER;
1517                 return false;
1518         }
1519
1520         int len;
1521
1522         while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1523                 if(len < 0) {
1524                         if(errno == EINTR)
1525                                 continue;
1526                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1527                         meshlink_errno = MESHLINK_ENETWORK;
1528                         return false;
1529                 }
1530
1531                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1532                         meshlink_errno = MESHLINK_EPEER;
1533                         return false;
1534                 }
1535         }
1536
1537         sptps_stop(&mesh->sptps);
1538         ecdsa_free(hiskey);
1539         ecdsa_free(key);
1540         closesocket(mesh->sock);
1541
1542         if(!mesh->success) {
1543                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1544                 meshlink_errno = MESHLINK_EPEER;
1545                 return false;
1546         }
1547
1548         return true;
1549
1550 invalid:
1551         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1552         meshlink_errno = MESHLINK_EINVAL;
1553         return false;
1554 }
1555
1556 char *meshlink_export(meshlink_handle_t *mesh) {
1557         if(!mesh) {
1558                 meshlink_errno = MESHLINK_EINVAL;
1559                 return NULL;
1560         }
1561
1562         char filename[PATH_MAX];
1563         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1564         FILE *f = fopen(filename, "r");
1565         if(!f) {
1566                 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1567                 meshlink_errno = MESHLINK_ESTORAGE;
1568                 return NULL;
1569         }
1570
1571         fseek(f, 0, SEEK_END);
1572         int fsize = ftell(f);
1573         rewind(f);
1574
1575         size_t len = fsize + 9 + strlen(mesh->self->name);
1576         char *buf = xmalloc(len);
1577         snprintf(buf, len, "Name = %s\n", mesh->self->name);
1578         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1579                 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1580                 fclose(f);
1581                 meshlink_errno = MESHLINK_ESTORAGE;
1582                 return NULL;
1583         }
1584
1585         fclose(f);
1586         buf[len - 1] = 0;
1587         return buf;
1588 }
1589
1590 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1591         if(!mesh || !data) {
1592                 meshlink_errno = MESHLINK_EINVAL;
1593                 return false;
1594         }
1595
1596         if(strncmp(data, "Name = ", 7)) {
1597                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1598                 meshlink_errno = MESHLINK_EPEER;
1599                 return false;
1600         }
1601
1602         char *end = strchr(data + 7, '\n');
1603         if(!end) {
1604                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1605                 meshlink_errno = MESHLINK_EPEER;
1606                 return false;
1607         }
1608
1609         int len = end - (data + 7);
1610         char name[len + 1];
1611         memcpy(name, data + 7, len);
1612         name[len] = 0;
1613         if(!check_id(name)) {
1614                 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1615                 meshlink_errno = MESHLINK_EPEER;
1616                 return false;
1617         }
1618
1619         char filename[PATH_MAX];
1620         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1621         if(!access(filename, F_OK)) {
1622                 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1623                 meshlink_errno = MESHLINK_EEXIST;
1624                 return false;
1625         }
1626
1627         if(errno != ENOENT) {
1628                 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1629                 meshlink_errno = MESHLINK_ESTORAGE;
1630                 return false;
1631         }
1632
1633         FILE *f = fopen(filename, "w");
1634         if(!f) {
1635                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1636                 meshlink_errno = MESHLINK_ESTORAGE;
1637                 return false;
1638         }
1639
1640         fwrite(end + 1, strlen(end + 1), 1, f);
1641         fclose(f);
1642
1643         load_all_nodes(mesh);
1644
1645         return true;
1646 }
1647
1648 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1649         if(!mesh || !node) {
1650                 meshlink_errno = MESHLINK_EINVAL;
1651                 return;
1652         }
1653
1654         node_t *n;
1655         n = (node_t*)node;
1656         n->status.blacklisted=true;
1657         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n",node->name);
1658
1659         //Make blacklisting persistent in the config file
1660         append_config_file(mesh, n->name, "blacklisted", "yes");
1661
1662         return;
1663 }
1664
1665 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1666         if(!mesh || !node) {
1667                 meshlink_errno = MESHLINK_EINVAL;
1668                 return;
1669         }
1670
1671         node_t *n = (node_t *)node;
1672         n->status.blacklisted = false;
1673
1674         //TODO: remove blacklisted = yes from the config file
1675
1676         return;
1677 }
1678
1679 /* Hint that a hostname may be found at an address
1680  * See header file for detailed comment.
1681  */
1682 extern void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
1683         if(!mesh || !node || !addr)
1684                 return;
1685         
1686         char *host = NULL, *port = NULL, *str = NULL;
1687         sockaddr2str((const sockaddr_t *)addr, &host, &port);
1688
1689         if(host && port) {
1690                 xasprintf(&str, "%s %s", host, port);
1691                 append_config_file(mesh, node->name, "Address", str);
1692         }
1693
1694         free(str);
1695         free(host);
1696         free(port);
1697
1698         // @TODO do we want to fire off a connection attempt right away?
1699 }
1700
1701 static void __attribute__((constructor)) meshlink_init(void) {
1702         crypto_init();
1703 }
1704
1705 static void __attribute__((destructor)) meshlink_exit(void) {
1706         crypto_exit();
1707 }
1708
1709 int cweight_from_dclass(dclass_t dclass)
1710 {
1711         switch(dclass)
1712         {
1713         case BACKBONE:
1714                 return 1;
1715
1716         case STATIONARY:
1717                 return 3;
1718
1719         case PORTABLE:
1720                 return 6;
1721         }
1722
1723         return 9;
1724 }
1725
1726 int max_ccount_from_dclass(dclass_t dclass)
1727 {
1728         switch(dclass)
1729         {
1730         case BACKBONE:
1731                 return 10000;
1732
1733         case STATIONARY:
1734                 return 100;
1735
1736         case PORTABLE:
1737                 return 3;
1738         }
1739
1740         return 3;
1741 }
1742
1743 bool dclass_ccounts_satisfied(dclass_t dclass, splay_tree_t* counts, int total_count)
1744 {
1745         // lookup keys
1746         dclass_ccount_t key_portable;
1747         key_portable.dclass = PORTABLE;
1748
1749         dclass_ccount_t key_stationary;
1750         key_stationary.dclass = STATIONARY;
1751
1752         dclass_ccount_t key_backbone;
1753         key_backbone.dclass = BACKBONE;
1754
1755         // check num of portable devices
1756         dclass_ccount_t* portable = splay_search(counts, &key_portable);
1757
1758         if(portable)
1759         {
1760                 if(portable->ccount > 9)
1761                         return true;
1762         }
1763
1764         // check num of stationary devices
1765         dclass_ccount_t* stationary = splay_search(counts, &key_stationary);
1766
1767         if(stationary)
1768         {
1769                 if(stationary->ccount > 6)
1770                         return true;
1771         }
1772
1773         // check num of backbone devices
1774         dclass_ccount_t* backbone = splay_search(counts, &key_backbone);
1775
1776         if(backbone)
1777         {
1778                 if(backbone->ccount > 3)
1779                         return true;
1780         }
1781
1782         // fallback
1783         if(total_count >= max_ccount_from_dclass(dclass))
1784                 return true;
1785
1786         return false;
1787 }
1788
1789 int dclass_ccount_compare(const void *a, const void *b)
1790 {
1791         const dclass_ccount_t* da = a;
1792         const dclass_ccount_t* db = b;
1793
1794         return da->dclass - db->dclass;
1795 }
1796
1797 dclass_ccount_t* dclass_ccount_alloc()
1798 {
1799         return xzalloc(sizeof(dclass_ccount_t));
1800 }
1801
1802 void dclass_ccount_delete(void *c)
1803 {
1804         free(c);
1805 }