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