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