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