]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
A first attempt at merging UTCP into MeshLink.
[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://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                         return false;
332                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
333                 closesocket(fd);
334                 if(result)
335                         return false;
336                 ai = ai->ai_next;
337         }
338
339         return true;
340 }
341
342 static int check_port(meshlink_handle_t *mesh) {
343         if(try_bind(655))
344                 return 655;
345
346         fprintf(stderr, "Warning: could not bind to port 655.\n");
347
348         for(int i = 0; i < 100; i++) {
349                 int port = 0x1000 + (rand() & 0x7fff);
350                 if(try_bind(port)) {
351                         char filename[PATH_MAX];
352                         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
353                         FILE *f = fopen(filename, "a");
354                         if(!f) {
355                                 fprintf(stderr, "Please change MeshLink's Port manually.\n");
356                                 return 0;
357                         }
358
359                         fprintf(f, "Port = %d\n", port);
360                         fclose(f);
361                         fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
362                         return port;
363                 }
364         }
365
366         fprintf(stderr, "Please change MeshLink's Port manually.\n");
367         return 0;
368 }
369
370 static bool finalize_join(meshlink_handle_t *mesh) {
371         char *name = xstrdup(get_value(mesh->data, "Name"));
372         if(!name) {
373                 fprintf(stderr, "No Name found in invitation!\n");
374                 return false;
375         }
376
377         if(!check_id(name)) {
378                 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
379                 return false;
380         }
381
382         char filename[PATH_MAX];
383         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
384
385         FILE *f = fopen(filename, "w");
386         if(!f) {
387                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
388                 return false;
389         }
390
391         fprintf(f, "Name = %s\n", name);
392
393         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
394         FILE *fh = fopen(filename, "w");
395         if(!fh) {
396                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
397                 fclose(f);
398                 return false;
399         }
400
401         // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
402         // Other chunks go unfiltered to their respective host config files
403         const char *p = mesh->data;
404         char *l, *value;
405
406         while((l = get_line(&p))) {
407                 // Ignore comments
408                 if(*l == '#')
409                         continue;
410
411                 // Split line into variable and value
412                 int len = strcspn(l, "\t =");
413                 value = l + len;
414                 value += strspn(value, "\t ");
415                 if(*value == '=') {
416                         value++;
417                         value += strspn(value, "\t ");
418                 }
419                 l[len] = 0;
420
421                 // Is it a Name?
422                 if(!strcasecmp(l, "Name"))
423                         if(strcmp(value, name))
424                                 break;
425                         else
426                                 continue;
427                 else if(!strcasecmp(l, "NetName"))
428                         continue;
429
430                 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
431                 bool found = false;
432                 int i;
433                 for(i = 0; variables[i].name; i++) {
434                         if(strcasecmp(l, variables[i].name))
435                                 continue;
436                         found = true;
437                         break;
438                 }
439
440                 // Ignore unknown and unsafe variables
441                 if(!found) {
442                         fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
443                         continue;
444                 } else if(!(variables[i].type & VAR_SAFE)) {
445                         fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
446                         continue;
447                 }
448
449                 // Copy the safe variable to the right config file
450                 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
451         }
452
453         fclose(f);
454
455         while(l && !strcasecmp(l, "Name")) {
456                 if(!check_id(value)) {
457                         fprintf(stderr, "Invalid Name found in invitation.\n");
458                         return false;
459                 }
460
461                 if(!strcmp(value, name)) {
462                         fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
463                         return false;
464                 }
465
466                 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
467                 f = fopen(filename, "w");
468
469                 if(!f) {
470                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
471                         return false;
472                 }
473
474                 while((l = get_line(&p))) {
475                         if(!strcmp(l, "#---------------------------------------------------------------#"))
476                                 continue;
477                         int len = strcspn(l, "\t =");
478                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
479                                 value = l + len;
480                                 value += strspn(value, "\t ");
481                                 if(*value == '=') {
482                                         value++;
483                                         value += strspn(value, "\t ");
484                                 }
485                                 l[len] = 0;
486                                 break;
487                         }
488
489                         fputs(l, f);
490                         fputc('\n', f);
491                 }
492
493                 fclose(f);
494         }
495
496         char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
497         if(!b64key)
498                 return false;
499
500         fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
501         fprintf(fh, "Port = %s\n", mesh->myport);
502
503         fclose(fh);
504
505         sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
506         free(b64key);
507
508         free(mesh->self->name);
509         free(mesh->self->connection->name);
510         mesh->self->name = xstrdup(name);
511         mesh->self->connection->name = xstrdup(name);
512
513         fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
514
515         load_all_nodes(mesh);
516
517         return true;
518 }
519
520 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
521         meshlink_handle_t* mesh = handle;
522         while(len) {
523                 int result = send(mesh->sock, data, len, 0);
524                 if(result == -1 && errno == EINTR)
525                         continue;
526                 else if(result <= 0)
527                         return false;
528                 data += result;
529                 len -= result;
530         }
531         return true;
532 }
533
534 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
535         meshlink_handle_t* mesh = handle;
536         switch(type) {
537                 case SPTPS_HANDSHAKE:
538                         return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
539
540                 case 0:
541                         mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
542                         memcpy(mesh->data + mesh->thedatalen, msg, len);
543                         mesh->thedatalen += len;
544                         mesh->data[mesh->thedatalen] = 0;
545                         break;
546
547                 case 1:
548                         return finalize_join(mesh);
549
550                 case 2:
551                         fprintf(stderr, "Invitation succesfully accepted.\n");
552                         shutdown(mesh->sock, SHUT_RDWR);
553                         mesh->success = true;
554                         break;
555
556                 default:
557                         return false;
558         }
559
560         return true;
561 }
562
563 static bool recvline(meshlink_handle_t* mesh, size_t len) {
564         char *newline = NULL;
565
566         if(!mesh->sock)
567                 abort();
568
569         while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
570                 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
571                 if(result == -1 && errno == EINTR)
572                         continue;
573                 else if(result <= 0)
574                         return false;
575                 mesh->blen += result;
576         }
577
578         if(newline - mesh->buffer >= len)
579                 return false;
580
581         len = newline - mesh->buffer;
582
583         memcpy(mesh->line, mesh->buffer, len);
584         mesh->line[len] = 0;
585         memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
586         mesh->blen -= len + 1;
587
588         return true;
589 }
590 static bool sendline(int fd, char *format, ...) {
591         static char buffer[4096];
592         char *p = buffer;
593         int blen = 0;
594         va_list ap;
595
596         va_start(ap, format);
597         blen = vsnprintf(buffer, sizeof buffer, format, ap);
598         va_end(ap);
599
600         if(blen < 1 || blen >= sizeof buffer)
601                 return false;
602
603         buffer[blen] = '\n';
604         blen++;
605
606         while(blen) {
607                 int result = send(fd, p, blen, MSG_NOSIGNAL);
608                 if(result == -1 && errno == EINTR)
609                         continue;
610                 else if(result <= 0)
611                         return false;
612                 p += result;
613                 blen -= result;
614         }
615
616         return true;
617 }
618
619 static const char *errstr[] = {
620         [MESHLINK_OK] = "No error",
621         [MESHLINK_ENOMEM] = "Out of memory",
622         [MESHLINK_ENOENT] = "No such node",
623 };
624
625 const char *meshlink_strerror(meshlink_errno_t errno) {
626         return errstr[errno];
627 }
628
629 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
630         ecdsa_t *key;
631         FILE *f;
632         char pubname[PATH_MAX], privname[PATH_MAX];
633
634         fprintf(stderr, "Generating ECDSA keypair:\n");
635
636         if(!(key = ecdsa_generate())) {
637                 fprintf(stderr, "Error during key generation!\n");
638                 return false;
639         } else
640                 fprintf(stderr, "Done.\n");
641
642         snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
643         f = fopen(privname, "w");
644
645         if(!f)
646                 return false;
647
648 #ifdef HAVE_FCHMOD
649         fchmod(fileno(f), 0600);
650 #endif
651
652         if(!ecdsa_write_pem_private_key(key, f)) {
653                 fprintf(stderr, "Error writing private key!\n");
654                 ecdsa_free(key);
655                 fclose(f);
656                 return false;
657         }
658
659         fclose(f);
660
661
662         snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
663         f = fopen(pubname, "a");
664
665         if(!f)
666                 return false;
667
668         char *pubkey = ecdsa_get_base64_public_key(key);
669         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
670         free(pubkey);
671
672         fclose(f);
673         ecdsa_free(key);
674
675         return true;
676 }
677
678 static bool meshlink_setup(meshlink_handle_t *mesh) {
679         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
680                 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
681                 return false;
682         }
683
684         char filename[PATH_MAX];
685         snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
686
687         if(mkdir(filename, 0777) && errno != EEXIST) {
688                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
689                 return false;
690         }
691
692         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
693
694         if(!access(filename, F_OK)) {
695                 fprintf(stderr, "Configuration file %s already exists!\n", filename);
696                 return false;
697         }
698
699         FILE *f = fopen(filename, "w");
700         if(!f) {
701                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
702                 return 1;
703         }
704
705         fprintf(f, "Name = %s\n", mesh->name);
706         fclose(f);
707
708         if(!ecdsa_keygen(mesh))
709                 return false;
710
711         check_port(mesh);
712
713         return true;
714 }
715
716 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
717         // Validate arguments provided by the application
718         bool usingname = false;
719
720         if(!confbase || !*confbase) {
721                 fprintf(stderr, "No confbase given!\n");
722                 return NULL;
723         }
724
725         if(!name || !*name) {
726                 fprintf(stderr, "No name given!\n");
727                 //return NULL;
728         }
729         else { //check name only if there is a name != NULL
730
731                 if(!check_id(name)) {
732                         fprintf(stderr, "Invalid name given!\n");
733                         return NULL;
734                 } else { usingname = true;}
735         }
736
737         meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
738         mesh->confbase = xstrdup(confbase);
739         if (usingname) mesh->name = xstrdup(name);
740         pthread_mutex_init ( &(mesh->outpacketqueue_mutex), NULL);
741         pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
742         mesh->threadstarted = false;
743         event_loop_init(&mesh->loop);
744         mesh->loop.data = mesh;
745
746         // TODO: should be set by a function.
747         mesh->debug_level = 5;
748
749         // Check whether meshlink.conf already exists
750
751         char filename[PATH_MAX];
752         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
753
754         if(access(filename, R_OK)) {
755                 if(errno == ENOENT) {
756                         // If not, create it
757                         meshlink_setup(mesh);
758                 } else {
759                         fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
760                         return meshlink_close(mesh), NULL;
761                 }
762         }
763
764         // Read the configuration
765
766         init_configuration(&mesh->config);
767
768         if(!read_server_config(mesh))
769                 return meshlink_close(mesh), NULL;
770
771 #ifdef HAVE_MINGW
772         struct WSAData wsa_state;
773         WSAStartup(MAKEWORD(2, 2), &wsa_state);
774 #endif
775
776         // Setup up everything
777         // TODO: we should not open listening sockets yet
778
779         if(!setup_network(mesh))
780                 return meshlink_close(mesh), NULL;
781
782         return mesh;
783 }
784
785 void *meshlink_main_loop(void *arg) {
786         meshlink_handle_t *mesh = arg;
787
788         try_outgoing_connections(mesh);
789
790         main_loop(mesh);
791
792         return NULL;
793 }
794
795 bool meshlink_start(meshlink_handle_t *mesh) {
796         // TODO: open listening sockets first
797
798         //Check that a valid name is set
799         if(!mesh->name ) {
800                 fprintf(stderr, "No name given!\n");
801                 return false;
802         }
803
804         // Start the main thread
805
806         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
807                 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
808                 memset(&mesh->thread, 0, sizeof mesh->thread);
809                 return false;
810         }
811
812         mesh->threadstarted=true;
813
814         return true;
815 }
816
817 void meshlink_stop(meshlink_handle_t *mesh) {
818         // Shut down the listening sockets to signal the main thread to shut down
819
820         for(int i = 0; i < mesh->listen_sockets; i++) {
821                 shutdown(mesh->listen_socket[i].tcp.fd, SHUT_RDWR);
822                 shutdown(mesh->listen_socket[i].udp.fd, SHUT_RDWR);
823         }
824
825         // Wait for the main thread to finish
826
827         pthread_join(mesh->thread, NULL);
828 }
829
830 void meshlink_close(meshlink_handle_t *mesh) {
831         // Close and free all resources used.
832
833         close_network_connections(mesh);
834
835         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
836
837         exit_configuration(&mesh->config);
838         event_loop_exit(&mesh->loop);
839
840         free(mesh);
841
842 #ifdef HAVE_MINGW
843         WSACleanup();
844 #endif
845 }
846
847 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
848         mesh->receive_cb = cb;
849 }
850
851 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
852         mesh->node_status_cb = cb;
853 }
854
855 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
856         mesh->log_cb = cb;
857         mesh->log_level = level;
858 }
859
860 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
861
862         /* If there is no outgoing list yet, create one. */
863
864         if(!mesh->outpacketqueue)
865                 mesh->outpacketqueue = list_alloc(NULL);
866
867         //add packet to the queue
868         outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
869         packet_in_queue->destination=destination;
870         packet_in_queue->data=data;
871         packet_in_queue->len=len;
872         pthread_mutex_lock(&(mesh->outpacketqueue_mutex));
873         list_insert_head(mesh->outpacketqueue,packet_in_queue);
874         pthread_mutex_unlock(&(mesh->outpacketqueue_mutex));
875
876         //notify event loop
877         signal_trigger(&(mesh->loop),&(mesh->datafromapp));
878         return true;
879 }
880
881 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
882         vpn_packet_t packet;
883         meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
884
885         outpacketqueue_t* p = list_get_tail(mesh->outpacketqueue);
886         if (p)
887         list_delete_tail(mesh->outpacketqueue);
888         else return ;
889
890         if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
891                 //log something
892                 return ;
893         }
894
895         packet.probe = false;
896         memset(hdr, 0, sizeof *hdr);
897         memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
898         memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
899
900         packet.len = sizeof *hdr + p->len;
901         memcpy(packet.data + sizeof *hdr, p->data, p->len);
902
903         mesh->self->in_packets++;
904         mesh->self->in_bytes += packet.len;
905         route(mesh, mesh->self, &packet);
906         return ;
907 }
908
909 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
910         return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
911 }
912
913 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
914         size_t i = 0;
915
916         //lock mesh->nodes
917         pthread_mutex_lock(&(mesh->nodes_mutex));
918
919         for splay_each(node_t, n, mesh->nodes) {
920                 if(i < nmemb)
921                         nodes[i] = (meshlink_node_t *)n;
922                 i++;
923         }
924
925         pthread_mutex_unlock(&(mesh->nodes_mutex));
926
927         return i;
928 }
929
930 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
931         if(*siglen < MESHLINK_SIGLEN)
932                 return false;
933         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature))
934                 return false;
935         *siglen = MESHLINK_SIGLEN;
936         return true;
937 }
938
939 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
940         if(siglen != MESHLINK_SIGLEN)
941                 return false;
942         struct node_t *n = (struct node_t *)source;
943         node_read_ecdsa_public_key(mesh, n);
944         if(!n->ecdsa)
945                 return false;
946         return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
947 }
948
949 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
950         char filename[PATH_MAX];
951
952         snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
953         if(mkdir(filename, 0700) && errno != EEXIST) {
954                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
955                 return false;
956         }
957
958         // Count the number of valid invitations, clean up old ones
959         DIR *dir = opendir(filename);
960         if(!dir) {
961                 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
962                 return false;
963         }
964
965         errno = 0;
966         int count = 0;
967         struct dirent *ent;
968         time_t deadline = time(NULL) - 604800; // 1 week in the past
969
970         while((ent = readdir(dir))) {
971                 if(strlen(ent->d_name) != 24)
972                         continue;
973                 char invname[PATH_MAX];
974                 struct stat st;
975                 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
976                 if(!stat(invname, &st)) {
977                         if(mesh->invitation_key && deadline < st.st_mtime)
978                                 count++;
979                         else
980                                 unlink(invname);
981                 } else {
982                         fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
983                         errno = 0;
984                 }
985         }
986
987         if(errno) {
988                 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
989                 closedir(dir);
990                 return false;
991         }
992
993         closedir(dir);
994
995         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
996
997         // Remove the key if there are no outstanding invitations.
998         if(!count) {
999                 unlink(filename);
1000                 if(mesh->invitation_key) {
1001                         ecdsa_free(mesh->invitation_key);
1002                         mesh->invitation_key = NULL;
1003                 }
1004         }
1005
1006         if(mesh->invitation_key)
1007                 return true;
1008
1009         // Create a new key if necessary.
1010         FILE *f = fopen(filename, "r");
1011         if(!f) {
1012                 if(errno != ENOENT) {
1013                         fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1014                         return false;
1015                 }
1016
1017                 mesh->invitation_key = ecdsa_generate();
1018                 if(!mesh->invitation_key) {
1019                         fprintf(stderr, "Could not generate a new key!\n");
1020                         return false;
1021                 }
1022                 f = fopen(filename, "w");
1023                 if(!f) {
1024                         fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1025                         return false;
1026                 }
1027                 chmod(filename, 0600);
1028                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1029                 fclose(f);
1030         } else {
1031                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1032                 fclose(f);
1033                 if(!mesh->invitation_key)
1034                         fprintf(stderr, "Could not read private key from %s\n", filename);
1035         }
1036
1037         return mesh->invitation_key;
1038 }
1039
1040 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1041         for(const char *p = address; *p; p++) {
1042                 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1043                         continue;
1044                 fprintf(stderr, "Invalid character in address: %s\n", address);
1045                 return false;
1046         }
1047
1048         return append_config_file(mesh, mesh->self->name, "Address", address);
1049 }
1050
1051 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1052         // Check validity of the new node's name
1053         if(!check_id(name)) {
1054                 fprintf(stderr, "Invalid name for node.\n");
1055                 return NULL;
1056         }
1057
1058         // Ensure no host configuration file with that name exists
1059         char filename[PATH_MAX];
1060         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1061         if(!access(filename, F_OK)) {
1062                 fprintf(stderr, "A host config file for %s already exists!\n", name);
1063                 return NULL;
1064         }
1065
1066         // Ensure no other nodes know about this name
1067         if(meshlink_get_node(mesh, name)) {
1068                 fprintf(stderr, "A node with name %s is already known!\n", name);
1069                 return NULL;
1070         }
1071
1072         // Get the local address
1073         char *address = get_my_hostname(mesh);
1074         if(!address) {
1075                 fprintf(stderr, "No Address known for ourselves!\n");
1076                 return NULL;
1077         }
1078
1079         if(!refresh_invitation_key(mesh))
1080                 return NULL;
1081
1082         char hash[64];
1083
1084         // Create a hash of the key.
1085         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1086         sha512(fingerprint, strlen(fingerprint), hash);
1087         b64encode_urlsafe(hash, hash, 18);
1088
1089         // Create a random cookie for this invitation.
1090         char cookie[25];
1091         randomize(cookie, 18);
1092
1093         // Create a filename that doesn't reveal the cookie itself
1094         char buf[18 + strlen(fingerprint)];
1095         char cookiehash[64];
1096         memcpy(buf, cookie, 18);
1097         memcpy(buf + 18, fingerprint, sizeof buf - 18);
1098         sha512(buf, sizeof buf, cookiehash);
1099         b64encode_urlsafe(cookiehash, cookiehash, 18);
1100
1101         b64encode_urlsafe(cookie, cookie, 18);
1102
1103         // Create a file containing the details of the invitation.
1104         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1105         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1106         if(!ifd) {
1107                 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1108                 return NULL;
1109         }
1110         FILE *f = fdopen(ifd, "w");
1111         if(!f)
1112                 abort();
1113
1114         // Fill in the details.
1115         fprintf(f, "Name = %s\n", name);
1116         //if(netname)
1117         //      fprintf(f, "NetName = %s\n", netname);
1118         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1119
1120         // Copy Broadcast and Mode
1121         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1122         FILE *tc = fopen(filename,  "r");
1123         if(tc) {
1124                 char buf[1024];
1125                 while(fgets(buf, sizeof buf, tc)) {
1126                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1127                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1128                                 fputs(buf, f);
1129                                 // Make sure there is a newline character.
1130                                 if(!strchr(buf, '\n'))
1131                                         fputc('\n', f);
1132                         }
1133                 }
1134                 fclose(tc);
1135         } else {
1136                 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1137                 return NULL;
1138         }
1139
1140         fprintf(f, "#---------------------------------------------------------------#\n");
1141         fprintf(f, "Name = %s\n", mesh->self->name);
1142
1143         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1144         fcopy(f, filename);
1145         fclose(f);
1146
1147         // Create an URL from the local address, key hash and cookie
1148         char *url;
1149         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1150
1151         return url;
1152 }
1153
1154 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1155         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1156         char copy[strlen(invitation) + 1];
1157         strcpy(copy, invitation);
1158
1159         // Split the invitation URL into hostname, port, key hash and cookie.
1160
1161         char *slash = strchr(copy, '/');
1162         if(!slash)
1163                 goto invalid;
1164
1165         *slash++ = 0;
1166
1167         if(strlen(slash) != 48)
1168                 goto invalid;
1169
1170         char *address = copy;
1171         char *port = NULL;
1172         if(*address == '[') {
1173                 address++;
1174                 char *bracket = strchr(address, ']');
1175                 if(!bracket)
1176                         goto invalid;
1177                 *bracket = 0;
1178                 if(bracket[1] == ':')
1179                         port = bracket + 2;
1180         } else {
1181                 port = strchr(address, ':');
1182                 if(port)
1183                         *port++ = 0;
1184         }
1185
1186         if(!port)
1187                 port = "655";
1188
1189         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1190                 goto invalid;
1191
1192         // Generate a throw-away key for the invitation.
1193         ecdsa_t *key = ecdsa_generate();
1194         if(!key)
1195                 return false;
1196
1197         char *b64key = ecdsa_get_base64_public_key(key);
1198
1199         //Before doing meshlink_join make sure we are not connected to another mesh
1200         if ( mesh->threadstarted ){
1201                 goto invalid;
1202         }
1203
1204         // Connect to the meshlink daemon mentioned in the URL.
1205         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1206         if(!ai)
1207                 return false;
1208
1209         mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1210         if(mesh->sock <= 0) {
1211                 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1212                 return false;
1213         }
1214
1215         if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1216                 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1217                 closesocket(mesh->sock);
1218                 return false;
1219         }
1220
1221         fprintf(stderr, "Connected to %s port %s...\n", address, port);
1222
1223         // Tell him we have an invitation, and give him our throw-away key.
1224
1225         mesh->blen = 0;
1226
1227         if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1228                 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1229                 closesocket(mesh->sock);
1230                 return false;
1231         }
1232
1233         char hisname[4096] = "";
1234         int code, hismajor, hisminor = 0;
1235
1236         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) {
1237                 fprintf(stderr, "Cannot read greeting from peer\n");
1238                 closesocket(mesh->sock);
1239                 return false;
1240         }
1241
1242         // Check if the hash of the key he gave us matches the hash in the URL.
1243         char *fingerprint = mesh->line + 2;
1244         char hishash[64];
1245         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1246                 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1247                 return false;
1248         }
1249         if(memcmp(hishash, mesh->hash, 18)) {
1250                 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1251                 return false;
1252
1253         }
1254
1255         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1256         if(!hiskey)
1257                 return false;
1258
1259         // Start an SPTPS session
1260         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1261                 return false;
1262
1263         // Feed rest of input buffer to SPTPS
1264         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1265                 return false;
1266
1267         int len;
1268
1269         while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1270                 if(len < 0) {
1271                         if(errno == EINTR)
1272                                 continue;
1273                         fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1274                         return false;
1275                 }
1276
1277                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1278                         return false;
1279         }
1280
1281         sptps_stop(&mesh->sptps);
1282         ecdsa_free(hiskey);
1283         ecdsa_free(key);
1284         closesocket(mesh->sock);
1285
1286         if(!mesh->success) {
1287                 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1288                 return false;
1289         }
1290
1291         return true;
1292
1293 invalid:
1294         fprintf(stderr, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1295         return false;
1296 }
1297
1298 char *meshlink_export(meshlink_handle_t *mesh) {
1299         char filename[PATH_MAX];
1300         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1301         FILE *f = fopen(filename, "r");
1302         if(!f) {
1303                 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
1304                 return NULL;
1305         }
1306
1307         fseek(f, 0, SEEK_END);
1308         int fsize = ftell(f);
1309         rewind(f);
1310
1311         size_t len = fsize + 9 + strlen(mesh->self->name);
1312         char *buf = xmalloc(len);
1313         snprintf(buf, len, "Name = %s\n", mesh->self->name);
1314         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1315                 fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno));
1316                 fclose(f);
1317                 return NULL;
1318         }
1319
1320         fclose(f);
1321         buf[len - 1] = 0;
1322         return buf;
1323 }
1324
1325 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1326         if(strncmp(data, "Name = ", 7)) {
1327                 fprintf(stderr, "Invalid data\n");
1328                 return false;
1329         }
1330
1331         char *end = strchr(data + 7, '\n');
1332         if(!end) {
1333                 fprintf(stderr, "Invalid data\n");
1334                 return false;
1335         }
1336
1337         int len = end - (data + 7);
1338         char name[len + 1];
1339         memcpy(name, data + 7, len);
1340         name[len] = 0;
1341         if(!check_id(name)) {
1342                 fprintf(stderr, "Invalid Name\n");
1343                 return false;
1344         }
1345
1346         char filename[PATH_MAX];
1347         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1348         if(!access(filename, F_OK)) {
1349                 fprintf(stderr, "File %s already exists, not importing\n", filename);
1350                 return false;
1351         }
1352
1353         if(errno != ENOENT) {
1354                 fprintf(stderr, "Error accessing %s: %s\n", filename, strerror(errno));
1355                 return false;
1356         }
1357
1358         FILE *f = fopen(filename, "w");
1359         if(!f) {
1360                 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1361                 return false;
1362         }
1363
1364         fwrite(end + 1, strlen(end + 1), 1, f);
1365         fclose(f);
1366
1367         load_all_nodes(mesh);
1368
1369         return true;
1370 }
1371
1372 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1373     node_t *n;
1374     n = (node_t*)node;
1375     n->status.blacklisted=true;
1376         fprintf(stderr, "Blacklisted %s.\n",node->name);
1377
1378         //Make blacklisting persistent in the config file
1379         append_config_file(mesh, n->name, "blacklisted", "yes");
1380     return;
1381
1382 }
1383
1384 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
1385         //TODO: implement
1386         return false;
1387 }
1388
1389 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
1390         //TODO: implement
1391 }
1392
1393 static int channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
1394         meshlink_channel_t *channel = connection->priv;
1395         node_t *n = channel->node;
1396         meshlink_handle_t *mesh = n->mesh;
1397         if(!channel->receive_cb)
1398                 return -1;
1399         else {
1400                 channel->receive_cb(mesh, channel, data, len);
1401                 return 0;
1402         }
1403 }
1404
1405 static int channel_send(struct utcp *utcp, const void *data, size_t len) {
1406         node_t *n = utcp->priv;
1407         meshlink_handle_t *mesh = n->mesh;
1408         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? len : -1;
1409 }
1410
1411 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
1412         mesh->channel_accept_cb = cb;
1413 }
1414
1415 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
1416         channel->receive_cb = cb;
1417 }
1418
1419 meshlink_channel_t *meshlink_channel_open(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len) {
1420         node_t *n = (node_t *)node;
1421         if(!n->utcp) {
1422                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
1423                 if(!n->utcp)
1424                         return NULL;
1425         }
1426         meshlink_channel_t *channel = xzalloc(sizeof *channel);
1427         channel->node = n;
1428         channel->receive_cb = cb;
1429         channel->c = utcp_connect(n->utcp, port, channel_recv, channel);
1430         if(!channel->c) {
1431                 free(channel);
1432                 return NULL;
1433         }
1434         return channel;
1435 }
1436
1437 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
1438         utcp_shutdown(channel->c, direction);
1439 }
1440
1441 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
1442         utcp_close(channel->c);
1443         free(channel);
1444 }
1445
1446 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
1447         // TODO: locking.
1448         // Ideally we want to put the data into the UTCP connection's send buffer.
1449         // Then, preferrably only if there is room in the receiver window,
1450         // kick the meshlink thread to go send packets.
1451         return utcp_send(channel->c, data, len);
1452 }
1453
1454 static void __attribute__((constructor)) meshlink_init(void) {
1455         crypto_init();
1456 }
1457
1458 static void __attribute__((destructor)) meshlink_exit(void) {
1459         crypto_exit();
1460 }