]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Don't generate a new ECDSA key in finalize_join().
[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 tinc.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 typedef struct {
25         const char *name;
26         int type;
27 } var_t;
28
29 #include "system.h"
30 #include <pthread.h>
31
32 #include "crypto.h"
33 #include "ecdsagen.h"
34 #include "meshlink_internal.h"
35 #include "netutl.h"
36 #include "node.h"
37 #include "protocol.h"
38 #include "route.h"
39 #include "utils.h"
40 #include "xalloc.h"
41 #include "ed25519/sha512.h"
42
43
44 //TODO: this can go away completely
45 const var_t variables[] = {
46         /* Server configuration */
47         {"AddressFamily", VAR_SERVER},
48         {"AutoConnect", VAR_SERVER | VAR_SAFE},
49         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
50         {"BindToInterface", VAR_SERVER},
51         {"Broadcast", VAR_SERVER | VAR_SAFE},
52         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
53         {"DecrementTTL", VAR_SERVER},
54         {"Device", VAR_SERVER},
55         {"DeviceType", VAR_SERVER},
56         {"DirectOnly", VAR_SERVER},
57         {"ECDSAPrivateKeyFile", VAR_SERVER},
58         {"ExperimentalProtocol", VAR_SERVER},
59         {"Forwarding", VAR_SERVER},
60         {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
61         {"Hostnames", VAR_SERVER},
62         {"IffOneQueue", VAR_SERVER},
63         {"Interface", VAR_SERVER},
64         {"KeyExpire", VAR_SERVER},
65         {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
66         {"LocalDiscovery", VAR_SERVER},
67         {"MACExpire", VAR_SERVER},
68         {"MaxConnectionBurst", VAR_SERVER},
69         {"MaxOutputBufferSize", VAR_SERVER},
70         {"MaxTimeout", VAR_SERVER},
71         {"Mode", VAR_SERVER | VAR_SAFE},
72         {"Name", VAR_SERVER},
73         {"PingInterval", VAR_SERVER},
74         {"PingTimeout", VAR_SERVER},
75         {"PriorityInheritance", VAR_SERVER},
76         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
77         {"PrivateKeyFile", VAR_SERVER},
78         {"ProcessPriority", VAR_SERVER},
79         {"Proxy", VAR_SERVER},
80         {"ReplayWindow", VAR_SERVER},
81         {"ScriptsExtension", VAR_SERVER},
82         {"ScriptsInterpreter", VAR_SERVER},
83         {"StrictSubnets", VAR_SERVER},
84         {"TunnelServer", VAR_SERVER},
85         {"VDEGroup", VAR_SERVER},
86         {"VDEPort", VAR_SERVER},
87         /* Host configuration */
88         {"Address", VAR_HOST | VAR_MULTIPLE},
89         {"Cipher", VAR_SERVER | VAR_HOST},
90         {"ClampMSS", VAR_SERVER | VAR_HOST},
91         {"Compression", VAR_SERVER | VAR_HOST},
92         {"Digest", VAR_SERVER | VAR_HOST},
93         {"ECDSAPublicKey", VAR_HOST},
94         {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
95         {"IndirectData", VAR_SERVER | VAR_HOST},
96         {"MACLength", VAR_SERVER | VAR_HOST},
97         {"PMTU", VAR_SERVER | VAR_HOST},
98         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
99         {"Port", VAR_HOST},
100         {"PublicKey", VAR_HOST | VAR_OBSOLETE},
101         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
102         {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
103         {"TCPOnly", VAR_SERVER | VAR_HOST},
104         {"Weight", VAR_HOST | VAR_SAFE},
105         {NULL, 0}
106 };
107
108 static bool fcopy(FILE *out, const char *filename) {
109         FILE *in = fopen(filename, "r");
110         if(!in) {
111                 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
112                 return false;
113         }
114
115         char buf[1024];
116         size_t len;
117         while((len = fread(buf, 1, sizeof buf, in)))
118                 fwrite(buf, len, 1, out);
119         fclose(in);
120         return true;
121 }
122
123 static int rstrip(char *value) {
124         int len = strlen(value);
125         while(len && strchr("\t\r\n ", value[len - 1]))
126                 value[--len] = 0;
127         return len;
128 }
129
130 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
131         char line[4096];
132         if(!filename || (*hostname && *port))
133                 return;
134
135         FILE *f = fopen(filename, "r");
136         if(!f)
137                 return;
138
139         while(fgets(line, sizeof line, f)) {
140                 if(!rstrip(line))
141                         continue;
142                 char *p = line, *q;
143                 p += strcspn(p, "\t =");
144                 if(!*p)
145                         continue;
146                 q = p + strspn(p, "\t ");
147                 if(*q == '=')
148                         q += 1 + strspn(q + 1, "\t ");
149                 *p = 0;
150                 p = q + strcspn(q, "\t ");
151                 if(*p)
152                         *p++ = 0;
153                 p += strspn(p, "\t ");
154                 p[strcspn(p, "\t ")] = 0;
155
156                 if(!*port && !strcasecmp(line, "Port")) {
157                         *port = xstrdup(q);
158                 } else if(!*hostname && !strcasecmp(line, "Address")) {
159                         *hostname = xstrdup(q);
160                         if(*p) {
161                                 free(*port);
162                                 *port = xstrdup(p);
163                         }
164                 }
165
166                 if(*hostname && *port)
167                         break;
168         }
169
170         fclose(f);
171 }
172 static char *get_my_hostname(meshlink_handle_t* mesh) {
173         char *hostname = NULL;
174         char *port = NULL;
175         char *hostport = NULL;
176         char *name = mesh->self->name;
177         char filename[PATH_MAX] = "";
178         char line[4096];
179         FILE *f;
180
181         // Use first Address statement in own host config file
182         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
183         scan_for_hostname(filename, &hostname, &port);
184
185         if(hostname)
186                 goto done;
187
188         // If that doesn't work, guess externally visible hostname
189         fprintf(stderr, "Trying to discover externally visible hostname...\n");
190         struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
191         struct addrinfo *aip = ai;
192         static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
193
194         while(aip) {
195                 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
196                 if(s >= 0) {
197                         if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
198                                 closesocket(s);
199                                 s = -1;
200                         }
201                 }
202                 if(s >= 0) {
203                         send(s, request, sizeof request - 1, 0);
204                         int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
205                         if(len > 0) {
206                                 line[len] = 0;
207                                 if(line[len - 1] == '\n')
208                                         line[--len] = 0;
209                                 char *p = strrchr(line, '\n');
210                                 if(p && p[1])
211                                         hostname = xstrdup(p + 1);
212                         }
213                         closesocket(s);
214                         if(hostname)
215                                 break;
216                 }
217                 aip = aip->ai_next;
218                 continue;
219         }
220
221         if(ai)
222                 freeaddrinfo(ai);
223
224         // Check that the hostname is reasonable
225         if(hostname) {
226                 for(char *p = hostname; *p; p++) {
227                         if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
228                                 continue;
229                         // If not, forget it.
230                         free(hostname);
231                         hostname = NULL;
232                         break;
233                 }
234         }
235
236         //if(!tty) {
237         //      if(!hostname) {
238         //              fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
239         //              return NULL;
240         //      }
241         //      goto save;
242         //}
243
244 again:
245         fprintf(stderr, "Please enter your host's external address or hostname");
246         if(hostname)
247                 fprintf(stderr, " [%s]", hostname);
248         fprintf(stderr, ": ");
249
250         if(!fgets(line, sizeof line, stdin)) {
251                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
252                 free(hostname);
253                 return NULL;
254         }
255
256         if(!rstrip(line)) {
257                 if(hostname)
258                         goto save;
259                 else
260                         goto again;
261         }
262
263         for(char *p = line; *p; p++) {
264                 if(isalnum(*p) || *p == '-' || *p == '.')
265                         continue;
266                 fprintf(stderr, "Invalid address or hostname.\n");
267                 goto again;
268         }
269
270         free(hostname);
271         hostname = xstrdup(line);
272
273 save:
274         f = fopen(filename, "a");
275         if(f) {
276                 fprintf(f, "\nAddress = %s\n", hostname);
277                 fclose(f);
278         } else {
279                 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
280         }
281
282 done:
283         if(port) {
284                 if(strchr(hostname, ':'))
285                         xasprintf(&hostport, "[%s]:%s", hostname, port);
286                 else
287                         xasprintf(&hostport, "%s:%s", hostname, port);
288         } else {
289                 if(strchr(hostname, ':'))
290                         xasprintf(&hostport, "[%s]", hostname);
291                 else
292                         hostport = xstrdup(hostname);
293         }
294
295         free(hostname);
296         free(port);
297         return hostport;
298 }
299
300 static char *get_line(const char **data) {
301         if(!data || !*data)
302                 return NULL;
303
304         if(!**data) {
305                 *data = NULL;
306                 return NULL;
307         }
308
309         static char line[1024];
310         const char *end = strchr(*data, '\n');
311         size_t len = end ? end - *data : strlen(*data);
312         if(len >= sizeof line) {
313                 fprintf(stderr, "Maximum line length exceeded!\n");
314                 return NULL;
315         }
316         if(len && !isprint(**data))
317                 abort();
318
319         memcpy(line, *data, len);
320         line[len] = 0;
321
322         if(end)
323                 *data = end + 1;
324         else
325                 *data = NULL;
326
327         return line;
328 }
329
330 static char *get_value(const char *data, const char *var) {
331         char *line = get_line(&data);
332         if(!line)
333                 return NULL;
334
335         char *sep = line + strcspn(line, " \t=");
336         char *val = sep + strspn(sep, " \t");
337         if(*val == '=')
338                 val += 1 + strspn(val + 1, " \t");
339         *sep = 0;
340         if(strcasecmp(line, var))
341                 return NULL;
342         return val;
343 }
344
345 static bool try_bind(int port) {
346         struct addrinfo *ai = NULL;
347         struct addrinfo hint = {
348                 .ai_flags = AI_PASSIVE,
349                 .ai_family = AF_UNSPEC,
350                 .ai_socktype = SOCK_STREAM,
351                 .ai_protocol = IPPROTO_TCP,
352         };
353
354         char portstr[16];
355         snprintf(portstr, sizeof portstr, "%d", port);
356
357         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
358                 return false;
359
360         while(ai) {
361                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
362                 if(!fd)
363                         return false;
364                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
365                 closesocket(fd);
366                 if(result)
367                         return false;
368                 ai = ai->ai_next;
369         }
370
371         return true;
372 }
373
374 static int check_port(meshlink_handle_t *mesh) {
375         if(try_bind(655))
376                 return 655;
377
378         fprintf(stderr, "Warning: could not bind to port 655.\n");
379
380         for(int i = 0; i < 100; i++) {
381                 int port = 0x1000 + (rand() & 0x7fff);
382                 if(try_bind(port)) {
383                         char filename[PATH_MAX];
384                         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
385                         FILE *f = fopen(filename, "a");
386                         if(!f) {
387                                 fprintf(stderr, "Please change MeshLink's Port manually.\n");
388                                 return 0;
389                         }
390
391                         fprintf(f, "Port = %d\n", port);
392                         fclose(f);
393                         fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
394                         return port;
395                 }
396         }
397
398         fprintf(stderr, "Please change MeshLink's Port manually.\n");
399         return 0;
400 }
401
402 static bool finalize_join(meshlink_handle_t *mesh) {
403         char *name = xstrdup(get_value(mesh->data, "Name"));
404         if(!name) {
405                 fprintf(stderr, "No Name found in invitation!\n");
406                 return false;
407         }
408
409         if(!check_id(name)) {
410                 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
411                 return false;
412         }
413
414         char filename[PATH_MAX];
415         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
416
417         FILE *f = fopen(filename, "w");
418         if(!f) {
419                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
420                 return false;
421         }
422
423         fprintf(f, "Name = %s\n", name);
424
425         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
426         FILE *fh = fopen(filename, "w");
427         if(!fh) {
428                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
429                 return false;
430         }
431
432         // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
433         // Other chunks go unfiltered to their respective host config files
434         const char *p = mesh->data;
435         char *l, *value;
436
437         while((l = get_line(&p))) {
438                 // Ignore comments
439                 if(*l == '#')
440                         continue;
441
442                 // Split line into variable and value
443                 int len = strcspn(l, "\t =");
444                 value = l + len;
445                 value += strspn(value, "\t ");
446                 if(*value == '=') {
447                         value++;
448                         value += strspn(value, "\t ");
449                 }
450                 l[len] = 0;
451
452                 // Is it a Name?
453                 if(!strcasecmp(l, "Name"))
454                         if(strcmp(value, name))
455                                 break;
456                         else
457                                 continue;
458                 else if(!strcasecmp(l, "NetName"))
459                         continue;
460
461                 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
462                 bool found = false;
463                 int i;
464                 for(i = 0; variables[i].name; i++) {
465                         if(strcasecmp(l, variables[i].name))
466                                 continue;
467                         found = true;
468                         break;
469                 }
470
471                 // Ignore unknown and unsafe variables
472                 if(!found) {
473                         fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
474                         continue;
475                 } else if(!(variables[i].type & VAR_SAFE)) {
476                         fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
477                         continue;
478                 }
479
480                 // Copy the safe variable to the right config file
481                 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
482         }
483
484         fclose(f);
485
486         while(l && !strcasecmp(l, "Name")) {
487                 if(!check_id(value)) {
488                         fprintf(stderr, "Invalid Name found in invitation.\n");
489                         return false;
490                 }
491
492                 if(!strcmp(value, name)) {
493                         fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
494                         return false;
495                 }
496
497                 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
498                 f = fopen(filename, "w");
499
500                 if(!f) {
501                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
502                         return false;
503                 }
504
505                 while((l = get_line(&p))) {
506                         if(!strcmp(l, "#---------------------------------------------------------------#"))
507                                 continue;
508                         int len = strcspn(l, "\t =");
509                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
510                                 value = l + len;
511                                 value += strspn(value, "\t ");
512                                 if(*value == '=') {
513                                         value++;
514                                         value += strspn(value, "\t ");
515                                 }
516                                 l[len] = 0;
517                                 break;
518                         }
519
520                         fputs(l, f);
521                         fputc('\n', f);
522                 }
523
524                 fclose(f);
525         }
526
527         char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
528         if(!b64key)
529                 return false;
530
531         fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
532         fprintf(fh, "Port = %s\n", mesh->myport);
533
534         fclose(fh);
535
536         sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
537         free(b64key);
538
539         fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
540
541         return true;
542 }
543
544 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
545         meshlink_handle_t* mesh = handle;
546         while(len) {
547                 int result = send(mesh->sock, data, len, 0);
548                 if(result == -1 && errno == EINTR)
549                         continue;
550                 else if(result <= 0)
551                         return false;
552                 data += result;
553                 len -= result;
554         }
555         return true;
556 }
557
558 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
559         meshlink_handle_t* mesh = handle;
560         switch(type) {
561                 case SPTPS_HANDSHAKE:
562                         return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
563
564                 case 0:
565                         mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
566                         memcpy(mesh->data + mesh->thedatalen, msg, len);
567                         mesh->thedatalen += len;
568                         mesh->data[mesh->thedatalen] = 0;
569                         break;
570
571                 case 1:
572                         return finalize_join(mesh);
573
574                 case 2:
575                         fprintf(stderr, "Invitation succesfully accepted.\n");
576                         shutdown(mesh->sock, SHUT_RDWR);
577                         mesh->success = true;
578                         break;
579
580                 default:
581                         return false;
582         }
583
584         return true;
585 }
586
587 static bool recvline(meshlink_handle_t* mesh, size_t len) {
588         char *newline = NULL;
589
590         if(!mesh->sock)
591                 abort();
592
593         while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
594                 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
595                 if(result == -1 && errno == EINTR)
596                         continue;
597                 else if(result <= 0)
598                         return false;
599                 mesh->blen += result;
600         }
601
602         if(newline - mesh->buffer >= len)
603                 return false;
604
605         len = newline - mesh->buffer;
606
607         memcpy(mesh->line, mesh->buffer, len);
608         mesh->line[len] = 0;
609         memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
610         mesh->blen -= len + 1;
611
612         return true;
613 }
614 static bool sendline(int fd, char *format, ...) {
615         static char buffer[4096];
616         char *p = buffer;
617         int blen = 0;
618         va_list ap;
619
620         va_start(ap, format);
621         blen = vsnprintf(buffer, sizeof buffer, format, ap);
622         va_end(ap);
623
624         if(blen < 1 || blen >= sizeof buffer)
625                 return false;
626
627         buffer[blen] = '\n';
628         blen++;
629
630         while(blen) {
631                 int result = send(fd, p, blen, MSG_NOSIGNAL);
632                 if(result == -1 && errno == EINTR)
633                         continue;
634                 else if(result <= 0)
635                         return false;
636                 p += result;
637                 blen -= result;
638         }
639
640         return true;
641 }
642
643 static const char *errstr[] = {
644         [MESHLINK_OK] = "No error",
645         [MESHLINK_ENOMEM] = "Out of memory",
646         [MESHLINK_ENOENT] = "No such node",
647 };
648
649 const char *meshlink_strerror(meshlink_errno_t errno) {
650         return errstr[errno];
651 }
652
653 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
654         ecdsa_t *key;
655         FILE *f;
656         char pubname[PATH_MAX], privname[PATH_MAX];
657
658         fprintf(stderr, "Generating ECDSA keypair:\n");
659
660         if(!(key = ecdsa_generate())) {
661                 fprintf(stderr, "Error during key generation!\n");
662                 return false;
663         } else
664                 fprintf(stderr, "Done.\n");
665
666         snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
667         f = fopen(privname, "w");
668
669         if(!f)
670                 return false;
671
672 #ifdef HAVE_FCHMOD
673         fchmod(fileno(f), 0600);
674 #endif
675
676         if(!ecdsa_write_pem_private_key(key, f)) {
677                 fprintf(stderr, "Error writing private key!\n");
678                 ecdsa_free(key);
679                 fclose(f);
680                 return false;
681         }
682
683         fclose(f);
684
685
686         snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
687         f = fopen(pubname, "a");
688
689         if(!f)
690                 return false;
691
692         char *pubkey = ecdsa_get_base64_public_key(key);
693         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
694         free(pubkey);
695
696         fclose(f);
697         ecdsa_free(key);
698
699         return true;
700 }
701
702 static bool meshlink_setup(meshlink_handle_t *mesh) {
703         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
704                 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
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                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
713                 return false;
714         }
715
716         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
717
718         if(!access(filename, F_OK)) {
719                 fprintf(stderr, "Configuration file %s already exists!\n", filename);
720                 return false;
721         }
722
723         FILE *f = fopen(filename, "w");
724         if(!f) {
725                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
726                 return 1;
727         }
728
729         fprintf(f, "Name = %s\n", mesh->name);
730         fclose(f);
731
732         if(!ecdsa_keygen(mesh))
733                 return false;
734
735         check_port(mesh);
736
737         return true;
738 }
739
740 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
741         // Validate arguments provided by the application
742
743         if(!confbase || !*confbase) {
744                 fprintf(stderr, "No confbase given!\n");
745                 return NULL;
746         }
747
748         if(!name || !*name) {
749                 fprintf(stderr, "No name given!\n");
750                 return NULL;
751         }
752
753         if(!check_id(name)) {
754                 fprintf(stderr, "Invalid name given!\n");
755                 return NULL;
756         }
757
758         meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
759         mesh->confbase = xstrdup(confbase);
760         mesh->name = xstrdup(name);
761         event_loop_init(&mesh->loop);
762         mesh->loop.data = mesh;
763
764         // TODO: should be set by a function.
765         mesh->debug_level = 5;
766
767         // Check whether meshlink.conf already exists
768
769         char filename[PATH_MAX];
770         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
771
772         if(access(filename, R_OK)) {
773                 if(errno == ENOENT) {
774                         // If not, create it
775                         meshlink_setup(mesh);
776                 } else {
777                         fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
778                         return meshlink_close(mesh), NULL;
779                 }
780         }
781
782         // Read the configuration
783
784         init_configuration(&mesh->config);
785
786         if(!read_server_config(mesh))
787                 return meshlink_close(mesh), NULL;
788
789         // Setup up everything
790         // TODO: we should not open listening sockets yet
791
792         if(!setup_network(mesh))
793                 return meshlink_close(mesh), NULL;
794
795         return mesh;
796 }
797
798 void *meshlink_main_loop(void *arg) {
799         meshlink_handle_t *mesh = arg;
800
801         try_outgoing_connections(mesh);
802
803         main_loop(mesh);
804
805         return NULL;
806 }
807
808 bool meshlink_start(meshlink_handle_t *mesh) {
809         // TODO: open listening sockets first
810
811         // Start the main thread
812
813         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
814                 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
815                 memset(&mesh->thread, 0, sizeof mesh->thread);
816                 return false;
817         }
818
819         return true;
820 }
821
822 void meshlink_stop(meshlink_handle_t *mesh) {
823         // TODO: close the listening sockets to signal the main thread to shut down
824
825         // Wait for the main thread to finish
826
827         pthread_join(mesh->thread, NULL);
828 }
829
830 void meshlink_close(meshlink_handle_t *mesh) {
831         // Close and free all resources used.
832
833         close_network_connections(mesh);
834
835         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
836
837         exit_configuration(&mesh->config);
838         event_loop_exit(&mesh->loop);
839 }
840
841 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
842         mesh->receive_cb = cb;
843 }
844
845 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
846         mesh->node_status_cb = cb;
847 }
848
849 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
850         mesh->log_cb = cb;
851         mesh->log_level = level;
852 }
853
854 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
855         vpn_packet_t packet;
856         meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
857         if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
858                 //log something
859                 return false;
860         }
861
862         packet.probe = false;
863         memset(hdr, 0, sizeof *hdr);
864         memcpy(hdr->destination, destination->name, sizeof hdr->destination);
865         memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
866
867         packet.len = sizeof *hdr + len;
868         memcpy(packet.data + sizeof *hdr, data, len);
869
870         mesh->self->in_packets++;
871         mesh->self->in_bytes += packet.len;
872         route(mesh, mesh->self, &packet);
873         return false;
874 }
875
876 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
877         return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
878 }
879
880 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
881         return 0;
882 }
883
884 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
885         return NULL;
886 }
887
888 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
889         return false;
890 }
891
892 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
893         char filename[PATH_MAX];
894
895         snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
896         if(mkdir(filename, 0700) && errno != EEXIST) {
897                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
898                 return NULL;
899         }
900
901         // Count the number of valid invitations, clean up old ones
902         DIR *dir = opendir(filename);
903         if(!dir) {
904                 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
905                 return NULL;
906         }
907
908         errno = 0;
909         int count = 0;
910         struct dirent *ent;
911         time_t deadline = time(NULL) - 604800; // 1 week in the past
912
913         while((ent = readdir(dir))) {
914                 if(strlen(ent->d_name) != 24)
915                         continue;
916                 char invname[PATH_MAX];
917                 struct stat st;
918                 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
919                 if(!stat(invname, &st)) {
920                         if(mesh->invitation_key && deadline < st.st_mtime)
921                                 count++;
922                         else
923                                 unlink(invname);
924                 } else {
925                         fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
926                         errno = 0;
927                 }
928         }
929
930         if(errno) {
931                 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
932                 closedir(dir);
933                 return false;
934         }
935
936         closedir(dir);
937
938         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
939
940         // Remove the key if there are no outstanding invitations.
941         if(!count) {
942                 unlink(filename);
943                 if(mesh->invitation_key) {
944                         ecdsa_free(mesh->invitation_key);
945                         mesh->invitation_key = NULL;
946                 }
947         }
948
949         if(mesh->invitation_key)
950                 return true;
951
952         // Create a new key if necessary.
953         FILE *f = fopen(filename, "r");
954         if(!f) {
955                 if(errno != ENOENT) {
956                         fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
957                         return NULL;
958                 }
959
960                 mesh->invitation_key = ecdsa_generate();
961                 if(!mesh->invitation_key) {
962                         fprintf(stderr, "Could not generate a new key!\n");
963                         return NULL;
964                 }
965                 f = fopen(filename, "w");
966                 if(!f) {
967                         fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
968                         return NULL;
969                 }
970                 chmod(filename, 0600);
971                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
972                 fclose(f);
973         } else {
974                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
975                 fclose(f);
976                 if(!mesh->invitation_key)
977                         fprintf(stderr, "Could not read private key from %s\n", filename);
978         }
979
980         return mesh->invitation_key;
981 }
982
983 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
984         // Check validity of the new node's name
985         if(!check_id(name)) {
986                 fprintf(stderr, "Invalid name for node.\n");
987                 return NULL;
988         }
989
990         // Ensure no host configuration file with that name exists
991         char filename[PATH_MAX];
992         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
993         if(!access(filename, F_OK)) {
994                 fprintf(stderr, "A host config file for %s already exists!\n", name);
995                 return NULL;
996         }
997
998         // Ensure no other nodes know about this name
999         if(meshlink_get_node(mesh, name)) {
1000                 fprintf(stderr, "A node with name %s is already known!\n", name);
1001                 return NULL;
1002         }
1003
1004         if(!refresh_invitation_key(mesh))
1005                 return NULL;
1006
1007         char hash[64];
1008
1009         // Create a hash of the key.
1010         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1011         sha512(fingerprint, strlen(fingerprint), hash);
1012         b64encode_urlsafe(hash, hash, 18);
1013
1014         // Create a random cookie for this invitation.
1015         char cookie[25];
1016         randomize(cookie, 18);
1017
1018         // Create a filename that doesn't reveal the cookie itself
1019         char buf[18 + strlen(fingerprint)];
1020         char cookiehash[64];
1021         memcpy(buf, cookie, 18);
1022         memcpy(buf + 18, fingerprint, sizeof buf - 18);
1023         sha512(buf, sizeof buf, cookiehash);
1024         b64encode_urlsafe(cookiehash, cookiehash, 18);
1025
1026         b64encode_urlsafe(cookie, cookie, 18);
1027
1028         // Create a file containing the details of the invitation.
1029         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1030         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1031         if(!ifd) {
1032                 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1033                 return NULL;
1034         }
1035         FILE *f = fdopen(ifd, "w");
1036         if(!f)
1037                 abort();
1038
1039         // Get the local address
1040         char *address = get_my_hostname(mesh);
1041
1042         // Fill in the details.
1043         fprintf(f, "Name = %s\n", name);
1044         //if(netname)
1045         //      fprintf(f, "NetName = %s\n", netname);
1046         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1047
1048         // Copy Broadcast and Mode
1049         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1050         FILE *tc = fopen(filename,  "r");
1051         if(tc) {
1052                 char buf[1024];
1053                 while(fgets(buf, sizeof buf, tc)) {
1054                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1055                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1056                                 fputs(buf, f);
1057                                 // Make sure there is a newline character.
1058                                 if(!strchr(buf, '\n'))
1059                                         fputc('\n', f);
1060                         }
1061                 }
1062                 fclose(tc);
1063         } else {
1064                 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1065                 return NULL;
1066         }
1067
1068         fprintf(f, "#---------------------------------------------------------------#\n");
1069         fprintf(f, "Name = %s\n", mesh->self->name);
1070
1071         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1072         fcopy(f, filename);
1073         fclose(f);
1074
1075         // Create an URL from the local address, key hash and cookie
1076         char *url;
1077         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1078
1079         return url;
1080 }
1081
1082 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1083         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1084         char copy[strlen(invitation) + 1];
1085         strcpy(copy, invitation);
1086
1087         // Split the invitation URL into hostname, port, key hash and cookie.
1088
1089         char *slash = strchr(copy, '/');
1090         if(!slash)
1091                 goto invalid;
1092
1093         *slash++ = 0;
1094
1095         if(strlen(slash) != 48)
1096                 goto invalid;
1097
1098         char *address = copy;
1099         char *port = NULL;
1100         if(*address == '[') {
1101                 address++;
1102                 char *bracket = strchr(address, ']');
1103                 if(!bracket)
1104                         goto invalid;
1105                 *bracket = 0;
1106                 if(bracket[1] == ':')
1107                         port = bracket + 2;
1108         } else {
1109                 port = strchr(address, ':');
1110                 if(port)
1111                         *port++ = 0;
1112         }
1113
1114         if(!*port)
1115                 port = "655";
1116
1117         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1118                 goto invalid;
1119
1120         // Generate a throw-away key for the invitation.
1121         ecdsa_t *key = ecdsa_generate();
1122         if(!key)
1123                 return false;
1124
1125         char *b64key = ecdsa_get_base64_public_key(key);
1126
1127         // Connect to the meshlink daemon mentioned in the URL.
1128         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1129         if(!ai)
1130                 return false;
1131
1132         mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1133         if(mesh->sock <= 0) {
1134                 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1135                 return false;
1136         }
1137
1138         if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1139                 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1140                 closesocket(mesh->sock);
1141                 return false;
1142         }
1143
1144         fprintf(stderr, "Connected to %s port %s...\n", address, port);
1145
1146         // Tell him we have an invitation, and give him our throw-away key.
1147
1148         mesh->blen = 0;
1149
1150         if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1151                 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1152                 closesocket(mesh->sock);
1153                 return false;
1154         }
1155
1156         char hisname[4096] = "";
1157         int code, hismajor, hisminor = 0;
1158
1159         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) {
1160                 fprintf(stderr, "Cannot read greeting from peer\n");
1161                 closesocket(mesh->sock);
1162                 return false;
1163         }
1164
1165         // Check if the hash of the key he gave us matches the hash in the URL.
1166         char *fingerprint = mesh->line + 2;
1167         char hishash[64];
1168         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1169                 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1170                 return false;
1171         }
1172         if(memcmp(hishash, mesh->hash, 18)) {
1173                 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1174                 return false;
1175
1176         }
1177
1178         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1179         if(!hiskey)
1180                 return false;
1181
1182         // Start an SPTPS session
1183         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1184                 return false;
1185
1186         // Feed rest of input buffer to SPTPS
1187         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1188                 return false;
1189
1190         int len;
1191
1192         while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1193                 if(len < 0) {
1194                         if(errno == EINTR)
1195                                 continue;
1196                         fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1197                         return false;
1198                 }
1199
1200                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1201                         return false;
1202         }
1203
1204         sptps_stop(&mesh->sptps);
1205         ecdsa_free(hiskey);
1206         ecdsa_free(key);
1207         closesocket(mesh->sock);
1208
1209         if(!mesh->success) {
1210                 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1211                 return false;
1212         }
1213
1214         return true;
1215
1216 invalid:
1217         fprintf(stderr, "Invalid invitation URL.\n");
1218         return false;
1219 }
1220
1221 char *meshlink_export(meshlink_handle_t *mesh) {
1222         return NULL;
1223 }
1224
1225 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1226         return false;
1227 }
1228
1229 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1230 }
1231
1232 static void __attribute__((constructor)) meshlink_init(void) {
1233         crypto_init();
1234 }
1235
1236 static void __attribute__((destructor)) meshlink_exit(void) {
1237         crypto_exit();
1238 }