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