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