]> git.meshlink.io Git - meshlink-tiny/blob - src/meshlink.c
64580cf5eaaa59790c3a924950cd0acfd7ce2ca7
[meshlink-tiny] / src / meshlink.c
1 /*
2     meshlink.c -- Implementation of the MeshLink API.
3     Copyright (C) 2014-2021 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
20 #include "system.h"
21 #include <pthread.h>
22
23 #include "crypto.h"
24 #include "ecdsagen.h"
25 #include "logger.h"
26 #include "meshlink_internal.h"
27 #include "net.h"
28 #include "netutl.h"
29 #include "node.h"
30 #include "packmsg.h"
31 #include "prf.h"
32 #include "protocol.h"
33 #include "route.h"
34 #include "sockaddr.h"
35 #include "utils.h"
36 #include "xalloc.h"
37 #include "ed25519/sha512.h"
38 #include "devtools.h"
39
40 #ifndef MSG_NOSIGNAL
41 #define MSG_NOSIGNAL 0
42 #endif
43 __thread meshlink_errno_t meshlink_errno;
44 meshlink_log_cb_t global_log_cb;
45 meshlink_log_level_t global_log_level;
46
47 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
48
49 static int rstrip(char *value) {
50         int len = strlen(value);
51
52         while(len && strchr("\t\r\n ", value[len - 1])) {
53                 value[--len] = 0;
54         }
55
56         return len;
57 }
58
59 static bool is_valid_hostname(const char *hostname) {
60         if(!*hostname) {
61                 return false;
62         }
63
64         for(const char *p = hostname; *p; p++) {
65                 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
66                         return false;
67                 }
68         }
69
70         return true;
71 }
72
73 static bool is_valid_port(const char *port) {
74         if(!*port) {
75                 return false;
76         }
77
78         if(isdigit(*port)) {
79                 char *end;
80                 unsigned long int result = strtoul(port, &end, 10);
81                 return result && result < 65536 && !*end;
82         }
83
84         for(const char *p = port; *p; p++) {
85                 if(!(isalnum(*p) || *p == '-')) {
86                         return false;
87                 }
88         }
89
90         return true;
91 }
92
93 static void set_timeout(int sock, int timeout) {
94 #ifdef _WIN32
95         DWORD tv = timeout;
96 #else
97         struct timeval tv;
98         tv.tv_sec = timeout / 1000;
99         tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
100 #endif
101         setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
102         setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
103 }
104
105 struct socket_in_netns_params {
106         int domain;
107         int type;
108         int protocol;
109         int netns;
110         int fd;
111 };
112
113 #ifdef HAVE_SETNS
114 static void *socket_in_netns_thread(void *arg) {
115         struct socket_in_netns_params *params = arg;
116
117         if(setns(params->netns, CLONE_NEWNET) == -1) {
118                 meshlink_errno = MESHLINK_EINVAL;
119                 return NULL;
120         }
121
122         params->fd = socket(params->domain, params->type, params->protocol);
123
124         return NULL;
125 }
126 #endif // HAVE_SETNS
127
128 static int socket_in_netns(int domain, int type, int protocol, int netns) {
129         if(netns == -1) {
130                 return socket(domain, type, protocol);
131         }
132
133 #ifdef HAVE_SETNS
134         struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
135
136         pthread_t thr;
137
138         if(pthread_create(&thr, NULL, socket_in_netns_thread, &params) == 0) {
139                 if(pthread_join(thr, NULL) != 0) {
140                         abort();
141                 }
142         }
143
144         return params.fd;
145 #else
146         return -1;
147 #endif // HAVE_SETNS
148
149 }
150
151 static bool write_main_config_files(meshlink_handle_t *mesh) {
152         if(!mesh->confbase) {
153                 return true;
154         }
155
156         uint8_t buf[4096];
157
158         /* Write the main config file */
159         packmsg_output_t out = {buf, sizeof buf};
160
161         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
162         packmsg_add_str(&out, mesh->name);
163         packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
164         packmsg_add_nil(&out); // Invitation keys are not supported
165         packmsg_add_uint16(&out, atoi(mesh->myport));
166
167         if(!packmsg_output_ok(&out)) {
168                 return false;
169         }
170
171         config_t config = {buf, packmsg_output_size(&out, buf)};
172
173         if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
174                 return false;
175         }
176
177         /* Write our own host config file */
178         if(!node_write_config(mesh, mesh->self, true)) {
179                 return false;
180         }
181
182         return true;
183 }
184
185 typedef struct {
186         meshlink_handle_t *mesh;
187         int sock;
188         char cookie[18 + 32];
189         char hash[18];
190         bool success;
191         sptps_t sptps;
192         char *data;
193         size_t thedatalen;
194         size_t blen;
195         char line[4096];
196         char buffer[4096];
197 } join_state_t;
198
199 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
200         meshlink_handle_t *mesh = state->mesh;
201         packmsg_input_t in = {buf, len};
202         uint32_t version = packmsg_get_uint32(&in);
203
204         if(version != MESHLINK_INVITATION_VERSION) {
205                 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
206                 return false;
207         }
208
209         char *name = packmsg_get_str_dup(&in);
210         packmsg_skip_element(&in); // submesh_name
211         dev_class_t devclass = packmsg_get_int32(&in);
212         uint32_t count = packmsg_get_array(&in);
213
214         if(!name || !check_id(name)) {
215                 logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
216                 free(name);
217                 return false;
218         }
219
220         if(!count) {
221                 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
222                 free(name);
223                 return false;
224         }
225
226         free(mesh->name);
227         free(mesh->self->name);
228         mesh->name = name;
229         mesh->self->name = xstrdup(name);
230         mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
231
232         // Initialize configuration directory
233         if(!config_init(mesh, "current")) {
234                 return false;
235         }
236
237         if(!write_main_config_files(mesh)) {
238                 return false;
239         }
240
241         // Write host config files
242         for(uint32_t i = 0; i < count; i++) {
243                 const void *data;
244                 uint32_t data_len = packmsg_get_bin_raw(&in, &data);
245
246                 if(!data_len) {
247                         logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
248                         return false;
249                 }
250
251                 packmsg_input_t in2 = {data, data_len};
252                 uint32_t version2 = packmsg_get_uint32(&in2);
253                 char *name2 = packmsg_get_str_dup(&in2);
254
255                 if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
256                         free(name2);
257                         packmsg_input_invalidate(&in);
258                         break;
259                 }
260
261                 if(!check_id(name2)) {
262                         free(name2);
263                         break;
264                 }
265
266                 if(!strcmp(name2, mesh->name)) {
267                         logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
268                         free(name2);
269                         meshlink_errno = MESHLINK_EPEER;
270                         return false;
271                 }
272
273                 node_t *n = new_node();
274                 n->name = name2;
275
276                 config_t config = {data, data_len};
277
278                 if(!node_read_from_config(mesh, n, &config)) {
279                         free_node(n);
280                         logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
281                         meshlink_errno = MESHLINK_EPEER;
282                         return false;
283                 }
284
285                 if(i == 0) {
286                         /* The first host config file is of the inviter itself;
287                          * remember the address we are currently using for the invitation connection.
288                          */
289                         sockaddr_t sa;
290                         socklen_t salen = sizeof(sa);
291
292                         if(getpeername(state->sock, &sa.sa, &salen) == 0) {
293                                 node_add_recent_address(mesh, n, &sa);
294                         }
295                 }
296
297                 if(!node_write_config(mesh, n, true)) {
298                         free_node(n);
299                         return false;
300                 }
301
302                 node_add(mesh, n);
303         }
304
305         /* Ensure the configuration directory metadata is on disk */
306         if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
307                 return false;
308         }
309
310         if(!mesh->inviter_commits_first) {
311                 devtool_set_inviter_commits_first(false);
312         }
313
314         sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
315
316         logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
317
318         return true;
319 }
320
321 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
322         (void)type;
323         join_state_t *state = handle;
324         const char *ptr = data;
325
326         while(len) {
327                 int result = send(state->sock, ptr, len, 0);
328
329                 if(result == -1 && errno == EINTR) {
330                         continue;
331                 } else if(result <= 0) {
332                         return false;
333                 }
334
335                 ptr += result;
336                 len -= result;
337         }
338
339         return true;
340 }
341
342 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
343         join_state_t *state = handle;
344         meshlink_handle_t *mesh = state->mesh;
345
346         if(mesh->inviter_commits_first) {
347                 switch(type) {
348                 case SPTPS_HANDSHAKE:
349                         return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
350
351                 case 1:
352                         break;
353
354                 case 0:
355                         if(!finalize_join(state, msg, len)) {
356                                 return false;
357                         }
358
359                         logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
360                         shutdown(state->sock, SHUT_RDWR);
361                         state->success = true;
362                         break;
363
364                 default:
365                         return false;
366                 }
367         } else {
368                 switch(type) {
369                 case SPTPS_HANDSHAKE:
370                         return sptps_send_record(&state->sptps, 0, state->cookie, 18);
371
372                 case 0:
373                         return finalize_join(state, msg, len);
374
375                 case 1:
376                         logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
377                         shutdown(state->sock, SHUT_RDWR);
378                         state->success = true;
379                         break;
380
381                 default:
382                         return false;
383                 }
384         }
385
386         return true;
387 }
388
389 static bool recvline(join_state_t *state) {
390         char *newline = NULL;
391
392         while(!(newline = memchr(state->buffer, '\n', state->blen))) {
393                 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
394
395                 if(result == -1 && errno == EINTR) {
396                         continue;
397                 } else if(result <= 0) {
398                         return false;
399                 }
400
401                 state->blen += result;
402         }
403
404         if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
405                 return false;
406         }
407
408         size_t len = newline - state->buffer;
409
410         memcpy(state->line, state->buffer, len);
411         state->line[len] = 0;
412         memmove(state->buffer, newline + 1, state->blen - len - 1);
413         state->blen -= len + 1;
414
415         return true;
416 }
417
418 static bool sendline(int fd, const char *format, ...) {
419         char buffer[4096];
420         char *p = buffer;
421         int blen = 0;
422         va_list ap;
423
424         va_start(ap, format);
425         blen = vsnprintf(buffer, sizeof(buffer), format, ap);
426         va_end(ap);
427
428         if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
429                 return false;
430         }
431
432         buffer[blen] = '\n';
433         blen++;
434
435         while(blen) {
436                 int result = send(fd, p, blen, MSG_NOSIGNAL);
437
438                 if(result == -1 && errno == EINTR) {
439                         continue;
440                 } else if(result <= 0) {
441                         return false;
442                 }
443
444                 p += result;
445                 blen -= result;
446         }
447
448         return true;
449 }
450
451 static const char *errstr[] = {
452         [MESHLINK_OK] = "No error",
453         [MESHLINK_EINVAL] = "Invalid argument",
454         [MESHLINK_ENOMEM] = "Out of memory",
455         [MESHLINK_ENOENT] = "No such node",
456         [MESHLINK_EEXIST] = "Node already exists",
457         [MESHLINK_EINTERNAL] = "Internal error",
458         [MESHLINK_ERESOLV] = "Could not resolve hostname",
459         [MESHLINK_ESTORAGE] = "Storage error",
460         [MESHLINK_ENETWORK] = "Network error",
461         [MESHLINK_EPEER] = "Error communicating with peer",
462         [MESHLINK_ENOTSUP] = "Operation not supported",
463         [MESHLINK_EBUSY] = "MeshLink instance already in use",
464         [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
465 };
466
467 const char *meshlink_strerror(meshlink_errno_t err) {
468         if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
469                 return "Invalid error code";
470         }
471
472         return errstr[err];
473 }
474
475 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
476         logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
477
478         mesh->private_key = ecdsa_generate();
479
480         if(!mesh->private_key) {
481                 logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
482                 meshlink_errno = MESHLINK_EINTERNAL;
483                 return false;
484         }
485
486         logger(mesh, MESHLINK_DEBUG, "Done.\n");
487
488         return true;
489 }
490
491 static struct timespec idle(event_loop_t *loop, void *data) {
492         (void)loop;
493         meshlink_handle_t *mesh = data;
494
495         if(mesh->peer && mesh->peer->utcp) {
496                 return utcp_timeout(mesh->peer->utcp);
497         } else {
498                 return (struct timespec) {
499                         3600, 0
500                 };
501         }
502 }
503
504 static bool meshlink_setup(meshlink_handle_t *mesh) {
505         if(!config_destroy(mesh->confbase, "new")) {
506                 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
507                 meshlink_errno = MESHLINK_ESTORAGE;
508                 return false;
509         }
510
511         if(!config_destroy(mesh->confbase, "old")) {
512                 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
513                 meshlink_errno = MESHLINK_ESTORAGE;
514                 return false;
515         }
516
517         if(!config_init(mesh, "current")) {
518                 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
519                 meshlink_errno = MESHLINK_ESTORAGE;
520                 return false;
521         }
522
523         if(!ecdsa_keygen(mesh)) {
524                 meshlink_errno = MESHLINK_EINTERNAL;
525                 return false;
526         }
527
528         mesh->myport = xstrdup("0");
529
530         /* Create a node for ourself */
531
532         mesh->self = new_node();
533         mesh->self->name = xstrdup(mesh->name);
534         mesh->self->devclass = mesh->devclass;
535         mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
536         mesh->self->session_id = mesh->session_id;
537
538         if(!write_main_config_files(mesh)) {
539                 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
540                 meshlink_errno = MESHLINK_ESTORAGE;
541                 return false;
542         }
543
544         /* Ensure the configuration directory metadata is on disk */
545         if(!config_sync(mesh, "current")) {
546                 return false;
547         }
548
549         return true;
550 }
551
552 static bool meshlink_read_config(meshlink_handle_t *mesh) {
553         config_t config;
554
555         if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
556                 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
557                 return false;
558         }
559
560         packmsg_input_t in = {config.buf, config.len};
561         const void *private_key;
562
563         uint32_t version = packmsg_get_uint32(&in);
564         char *name = packmsg_get_str_dup(&in);
565         uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
566         packmsg_skip_element(&in); // Invitation key is not supported
567         uint16_t myport = packmsg_get_uint16(&in);
568
569         if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96) {
570                 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
571                 free(name);
572                 config_free(&config);
573                 return false;
574         }
575
576         if(mesh->name && strcmp(mesh->name, name)) {
577                 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
578                 meshlink_errno = MESHLINK_ESTORAGE;
579                 free(name);
580                 config_free(&config);
581                 return false;
582         }
583
584         free(mesh->name);
585         mesh->name = name;
586         xasprintf(&mesh->myport, "%u", myport);
587         mesh->private_key = ecdsa_set_private_key(private_key);
588         config_free(&config);
589
590         /* Create a node for ourself and read our host configuration file */
591
592         mesh->self = new_node();
593         mesh->self->name = xstrdup(name);
594         mesh->self->devclass = mesh->devclass;
595         mesh->self->session_id = mesh->session_id;
596
597         if(!node_read_public_key(mesh, mesh->self)) {
598                 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
599                 meshlink_errno = MESHLINK_ESTORAGE;
600                 free_node(mesh->self);
601                 mesh->self = NULL;
602                 return false;
603         }
604
605         return true;
606 }
607
608 #ifdef HAVE_SETNS
609 static void *setup_network_in_netns_thread(void *arg) {
610         meshlink_handle_t *mesh = arg;
611
612         if(setns(mesh->netns, CLONE_NEWNET) != 0) {
613                 return NULL;
614         }
615
616         bool success = setup_network(mesh);
617         return success ? arg : NULL;
618 }
619 #endif // HAVE_SETNS
620
621 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
622         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
623
624         if(!confbase || !*confbase) {
625                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
626                 meshlink_errno = MESHLINK_EINVAL;
627                 return NULL;
628         }
629
630         if(!appname || !*appname) {
631                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
632                 meshlink_errno = MESHLINK_EINVAL;
633                 return NULL;
634         }
635
636         if(strchr(appname, ' ')) {
637                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
638                 meshlink_errno = MESHLINK_EINVAL;
639                 return NULL;
640         }
641
642         if(name && !check_id(name)) {
643                 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
644                 meshlink_errno = MESHLINK_EINVAL;
645                 return NULL;
646         }
647
648         if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
649                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
650                 meshlink_errno = MESHLINK_EINVAL;
651                 return NULL;
652         }
653
654         meshlink_open_params_t *params = xzalloc(sizeof * params);
655
656         params->confbase = xstrdup(confbase);
657         params->name = name ? xstrdup(name) : NULL;
658         params->appname = xstrdup(appname);
659         params->devclass = devclass;
660         params->netns = -1;
661
662         xasprintf(&params->lock_filename, "%s" SLASH "meshlink.lock", confbase);
663
664         return params;
665 }
666
667 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
668         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
669
670         if(!params) {
671                 meshlink_errno = MESHLINK_EINVAL;
672                 return false;
673         }
674
675         params->netns = netns;
676
677         return true;
678 }
679
680 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
681         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
682
683         if(!params) {
684                 meshlink_errno = MESHLINK_EINVAL;
685                 return false;
686         }
687
688         if((!key && keylen) || (key && !keylen)) {
689                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
690                 meshlink_errno = MESHLINK_EINVAL;
691                 return false;
692         }
693
694         params->key = key;
695         params->keylen = keylen;
696
697         return true;
698 }
699
700 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
701         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
702
703         if(!params) {
704                 meshlink_errno = MESHLINK_EINVAL;
705                 return false;
706         }
707
708         params->storage_policy = policy;
709
710         return true;
711 }
712
713 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
714         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
715
716         if(!params || !filename) {
717                 meshlink_errno = MESHLINK_EINVAL;
718                 return false;
719         }
720
721         free(params->lock_filename);
722         params->lock_filename = xstrdup(filename);
723
724         return true;
725 }
726
727 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
728         logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
729
730         if(!mesh || !new_key || !new_keylen) {
731                 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
732                 meshlink_errno = MESHLINK_EINVAL;
733                 return false;
734         }
735
736         if(pthread_mutex_lock(&mesh->mutex) != 0) {
737                 abort();
738         }
739
740         // Create hash for the new key
741         void *new_config_key;
742         new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
743
744         if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
745                 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
746                 meshlink_errno = MESHLINK_EINTERNAL;
747                 pthread_mutex_unlock(&mesh->mutex);
748                 return false;
749         }
750
751         // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
752
753         if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
754                 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
755                 meshlink_errno = MESHLINK_ESTORAGE;
756                 pthread_mutex_unlock(&mesh->mutex);
757                 return false;
758         }
759
760         devtool_keyrotate_probe(1);
761
762         // Rename confbase/current/ to confbase/old
763
764         if(!config_rename(mesh, "current", "old")) {
765                 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
766                 meshlink_errno = MESHLINK_ESTORAGE;
767                 pthread_mutex_unlock(&mesh->mutex);
768                 return false;
769         }
770
771         devtool_keyrotate_probe(2);
772
773         // Rename confbase/new/ to confbase/current
774
775         if(!config_rename(mesh, "new", "current")) {
776                 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
777                 meshlink_errno = MESHLINK_ESTORAGE;
778                 pthread_mutex_unlock(&mesh->mutex);
779                 return false;
780         }
781
782         devtool_keyrotate_probe(3);
783
784         // Cleanup the "old" confbase sub-directory
785
786         if(!config_destroy(mesh->confbase, "old")) {
787                 pthread_mutex_unlock(&mesh->mutex);
788                 return false;
789         }
790
791         // Change the mesh handle key with new key
792
793         free(mesh->config_key);
794         mesh->config_key = new_config_key;
795
796         pthread_mutex_unlock(&mesh->mutex);
797
798         return true;
799 }
800
801 void meshlink_open_params_free(meshlink_open_params_t *params) {
802         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
803
804         if(!params) {
805                 meshlink_errno = MESHLINK_EINVAL;
806                 return;
807         }
808
809         free(params->confbase);
810         free(params->name);
811         free(params->appname);
812         free(params->lock_filename);
813
814         free(params);
815 }
816
817 /// Device class traits
818 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
819         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
820         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
821         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 },     // DEV_CLASS_PORTABLE
822         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 },     // DEV_CLASS_UNKNOWN
823 };
824
825 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
826         logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
827
828         if(!confbase || !*confbase) {
829                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
830                 meshlink_errno = MESHLINK_EINVAL;
831                 return NULL;
832         }
833
834         char lock_filename[PATH_MAX];
835         snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
836
837         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
838         meshlink_open_params_t params = {
839                 .confbase = (char *)confbase,
840                 .lock_filename = lock_filename,
841                 .name = (char *)name,
842                 .appname = (char *)appname,
843                 .devclass = devclass,
844                 .netns = -1,
845         };
846
847         return meshlink_open_ex(&params);
848 }
849
850 meshlink_handle_t *meshlink_open_encrypted(const char *confbase, const char *name, const char *appname, dev_class_t devclass, const void *key, size_t keylen) {
851         logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
852
853         if(!confbase || !*confbase) {
854                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
855                 meshlink_errno = MESHLINK_EINVAL;
856                 return NULL;
857         }
858
859         char lock_filename[PATH_MAX];
860         snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
861
862         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
863         meshlink_open_params_t params = {
864                 .confbase = (char *)confbase,
865                 .lock_filename = lock_filename,
866                 .name = (char *)name,
867                 .appname = (char *)appname,
868                 .devclass = devclass,
869                 .netns = -1,
870         };
871
872         if(!meshlink_open_params_set_storage_key(&params, key, keylen)) {
873                 return false;
874         }
875
876         return meshlink_open_ex(&params);
877 }
878
879 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
880         logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
881
882         if(!name) {
883                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
884                 meshlink_errno = MESHLINK_EINVAL;
885                 return NULL;
886         }
887
888         if(!check_id(name)) {
889                 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
890                 meshlink_errno = MESHLINK_EINVAL;
891                 return NULL;
892         }
893
894         if(!appname || !*appname) {
895                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
896                 meshlink_errno = MESHLINK_EINVAL;
897                 return NULL;
898         }
899
900         if(strchr(appname, ' ')) {
901                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
902                 meshlink_errno = MESHLINK_EINVAL;
903                 return NULL;
904         }
905
906         if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
907                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
908                 meshlink_errno = MESHLINK_EINVAL;
909                 return NULL;
910         }
911
912         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
913         meshlink_open_params_t params = {
914                 .name = (char *)name,
915                 .appname = (char *)appname,
916                 .devclass = devclass,
917                 .netns = -1,
918         };
919
920         return meshlink_open_ex(&params);
921 }
922
923 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
924         logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
925
926         // Validate arguments provided by the application
927         if(!params->appname || !*params->appname) {
928                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
929                 meshlink_errno = MESHLINK_EINVAL;
930                 return NULL;
931         }
932
933         if(strchr(params->appname, ' ')) {
934                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
935                 meshlink_errno = MESHLINK_EINVAL;
936                 return NULL;
937         }
938
939         if(params->name && !check_id(params->name)) {
940                 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
941                 meshlink_errno = MESHLINK_EINVAL;
942                 return NULL;
943         }
944
945         if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
946                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
947                 meshlink_errno = MESHLINK_EINVAL;
948                 return NULL;
949         }
950
951         if((params->key && !params->keylen) || (!params->key && params->keylen)) {
952                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
953                 meshlink_errno = MESHLINK_EINVAL;
954                 return NULL;
955         }
956
957         meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
958
959         if(params->confbase) {
960                 mesh->confbase = xstrdup(params->confbase);
961         }
962
963         mesh->appname = xstrdup(params->appname);
964         mesh->devclass = params->devclass;
965         mesh->netns = params->netns;
966         mesh->log_cb = global_log_cb;
967         mesh->log_level = global_log_level;
968         mesh->packet = xmalloc(sizeof(vpn_packet_t));
969
970         randomize(&mesh->prng_state, sizeof(mesh->prng_state));
971
972         do {
973                 randomize(&mesh->session_id, sizeof(mesh->session_id));
974         } while(mesh->session_id == 0);
975
976         memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
977
978         mesh->name = params->name ? xstrdup(params->name) : NULL;
979
980         // Hash the key
981         if(params->key) {
982                 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
983
984                 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
985                         logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
986                         meshlink_close(mesh);
987                         meshlink_errno = MESHLINK_EINTERNAL;
988                         return NULL;
989                 }
990         }
991
992         // initialize mutexes and conds
993         pthread_mutexattr_t attr;
994         pthread_mutexattr_init(&attr);
995
996         if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
997                 abort();
998         }
999
1000         pthread_mutex_init(&mesh->mutex, &attr);
1001         pthread_cond_init(&mesh->cond, NULL);
1002
1003         mesh->threadstarted = false;
1004         event_loop_init(&mesh->loop);
1005         mesh->loop.data = mesh;
1006
1007         meshlink_queue_init(&mesh->outpacketqueue);
1008
1009         // Atomically lock the configuration directory.
1010         if(!main_config_lock(mesh, params->lock_filename)) {
1011                 meshlink_close(mesh);
1012                 return NULL;
1013         }
1014
1015         // If no configuration exists yet, create it.
1016
1017         bool new_configuration = false;
1018
1019         if(!meshlink_confbase_exists(mesh)) {
1020                 if(!mesh->name) {
1021                         logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1022                         meshlink_close(mesh);
1023                         meshlink_errno = MESHLINK_ESTORAGE;
1024                         return NULL;
1025                 }
1026
1027                 if(!meshlink_setup(mesh)) {
1028                         logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1029                         meshlink_close(mesh);
1030                         return NULL;
1031                 }
1032
1033                 new_configuration = true;
1034         } else {
1035                 if(!meshlink_read_config(mesh)) {
1036                         logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1037                         meshlink_close(mesh);
1038                         return NULL;
1039                 }
1040         }
1041
1042         mesh->storage_policy = params->storage_policy;
1043
1044 #ifdef HAVE_MINGW
1045         struct WSAData wsa_state;
1046         WSAStartup(MAKEWORD(2, 2), &wsa_state);
1047 #endif
1048
1049         // Setup up everything
1050         // TODO: we should not open listening sockets yet
1051
1052         bool success = false;
1053
1054         if(mesh->netns != -1) {
1055 #ifdef HAVE_SETNS
1056                 pthread_t thr;
1057
1058                 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1059                         void *retval = NULL;
1060                         success = pthread_join(thr, &retval) == 0 && retval;
1061                 }
1062
1063 #else
1064                 meshlink_errno = MESHLINK_EINTERNAL;
1065                 return NULL;
1066
1067 #endif // HAVE_SETNS
1068         } else {
1069                 success = setup_network(mesh);
1070         }
1071
1072         if(!success) {
1073                 meshlink_close(mesh);
1074                 meshlink_errno = MESHLINK_ENETWORK;
1075                 return NULL;
1076         }
1077
1078         if(!node_write_config(mesh, mesh->self, new_configuration)) {
1079                 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1080                 return NULL;
1081         }
1082
1083         idle_set(&mesh->loop, idle, mesh);
1084
1085         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1086         return mesh;
1087 }
1088
1089 static void *meshlink_main_loop(void *arg) {
1090         meshlink_handle_t *mesh = arg;
1091
1092         if(mesh->netns != -1) {
1093 #ifdef HAVE_SETNS
1094
1095                 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1096                         pthread_cond_signal(&mesh->cond);
1097                         return NULL;
1098                 }
1099
1100 #else
1101                 pthread_cond_signal(&mesh->cond);
1102                 return NULL;
1103 #endif // HAVE_SETNS
1104         }
1105
1106         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1107                 abort();
1108         }
1109
1110         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1111         pthread_cond_broadcast(&mesh->cond);
1112         main_loop(mesh);
1113         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1114
1115         pthread_mutex_unlock(&mesh->mutex);
1116
1117         return NULL;
1118 }
1119
1120 bool meshlink_start(meshlink_handle_t *mesh) {
1121         if(!mesh) {
1122                 meshlink_errno = MESHLINK_EINVAL;
1123                 return false;
1124         }
1125
1126         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1127
1128         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1129                 abort();
1130         }
1131
1132         assert(mesh->self);
1133         assert(mesh->private_key);
1134         assert(mesh->self->ecdsa);
1135         assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1136
1137         if(mesh->threadstarted) {
1138                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1139                 pthread_mutex_unlock(&mesh->mutex);
1140                 return true;
1141         }
1142
1143         // Reset node connection timers
1144         if(mesh->peer) {
1145                 mesh->peer->last_connect_try = 0;
1146         }
1147
1148         //Check that a valid name is set
1149         if(!mesh->name) {
1150                 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1151                 meshlink_errno = MESHLINK_EINVAL;
1152                 pthread_mutex_unlock(&mesh->mutex);
1153                 return false;
1154         }
1155
1156         init_outgoings(mesh);
1157
1158         // Start the main thread
1159
1160         event_loop_start(&mesh->loop);
1161
1162         // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1163         pthread_attr_t attr;
1164         pthread_attr_init(&attr);
1165         pthread_attr_setstacksize(&attr, 1024 * 1024);
1166
1167         if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1168                 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1169                 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1170                 meshlink_errno = MESHLINK_EINTERNAL;
1171                 event_loop_stop(&mesh->loop);
1172                 pthread_mutex_unlock(&mesh->mutex);
1173                 return false;
1174         }
1175
1176         pthread_cond_wait(&mesh->cond, &mesh->mutex);
1177         mesh->threadstarted = true;
1178
1179         pthread_mutex_unlock(&mesh->mutex);
1180         return true;
1181 }
1182
1183 void meshlink_stop(meshlink_handle_t *mesh) {
1184         logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1185
1186         if(!mesh) {
1187                 meshlink_errno = MESHLINK_EINVAL;
1188                 return;
1189         }
1190
1191         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1192                 abort();
1193         }
1194
1195         // Shut down the main thread
1196         event_loop_stop(&mesh->loop);
1197
1198         // TODO: send something to a local socket to kick the event loop
1199
1200         if(mesh->threadstarted) {
1201                 // Wait for the main thread to finish
1202                 pthread_mutex_unlock(&mesh->mutex);
1203
1204                 if(pthread_join(mesh->thread, NULL) != 0) {
1205                         abort();
1206                 }
1207
1208                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1209                         abort();
1210                 }
1211
1212                 mesh->threadstarted = false;
1213         }
1214
1215         // Close all metaconnections
1216         if(mesh->connection) {
1217                 mesh->connection->outgoing = NULL;
1218                 terminate_connection(mesh, mesh->connection, false);
1219         }
1220
1221         exit_outgoings(mesh);
1222
1223         // Try to write out any changed node config files, ignore errors at this point.
1224         if(mesh->peer && mesh->peer->status.dirty) {
1225                 if(!node_write_config(mesh, mesh->peer, false)) {
1226                         // ignore
1227                 }
1228         }
1229
1230         pthread_mutex_unlock(&mesh->mutex);
1231 }
1232
1233 void meshlink_close(meshlink_handle_t *mesh) {
1234         logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1235
1236         if(!mesh) {
1237                 meshlink_errno = MESHLINK_EINVAL;
1238                 return;
1239         }
1240
1241         // stop can be called even if mesh has not been started
1242         meshlink_stop(mesh);
1243
1244         // lock is not released after this
1245         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1246                 abort();
1247         }
1248
1249         // Close and free all resources used.
1250
1251         close_network_connections(mesh);
1252
1253         logger(mesh, MESHLINK_INFO, "Terminating");
1254
1255         event_loop_exit(&mesh->loop);
1256
1257 #ifdef HAVE_MINGW
1258
1259         if(mesh->confbase) {
1260                 WSACleanup();
1261         }
1262
1263 #endif
1264
1265         if(mesh->netns != -1) {
1266                 close(mesh->netns);
1267         }
1268
1269         for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1270                 free(packet);
1271         }
1272
1273         meshlink_queue_exit(&mesh->outpacketqueue);
1274
1275         free(mesh->name);
1276         free(mesh->appname);
1277         free(mesh->confbase);
1278         free(mesh->config_key);
1279         free(mesh->external_address_url);
1280         free(mesh->packet);
1281         ecdsa_free(mesh->private_key);
1282
1283         main_config_unlock(mesh);
1284
1285         pthread_mutex_unlock(&mesh->mutex);
1286         pthread_mutex_destroy(&mesh->mutex);
1287
1288         memset(mesh, 0, sizeof(*mesh));
1289
1290         free(mesh);
1291 }
1292
1293 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1294         logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1295
1296         if(!params) {
1297                 meshlink_errno = MESHLINK_EINVAL;
1298                 return false;
1299         }
1300
1301         if(!params->confbase) {
1302                 /* Ephemeral instances */
1303                 return true;
1304         }
1305
1306         /* Exit early if the confbase directory itself doesn't exist */
1307         if(access(params->confbase, F_OK) && errno == ENOENT) {
1308                 return true;
1309         }
1310
1311         /* Take the lock the same way meshlink_open() would. */
1312         FILE *lockfile = fopen(params->lock_filename, "w+");
1313
1314         if(!lockfile) {
1315                 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1316                 meshlink_errno = MESHLINK_ESTORAGE;
1317                 return false;
1318         }
1319
1320 #ifdef FD_CLOEXEC
1321         fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1322 #endif
1323
1324 #ifdef HAVE_MINGW
1325         // TODO: use _locking()?
1326 #else
1327
1328         if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1329                 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
1330                 fclose(lockfile);
1331                 meshlink_errno = MESHLINK_EBUSY;
1332                 return false;
1333         }
1334
1335 #endif
1336
1337         if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
1338                 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
1339                 return false;
1340         }
1341
1342         if(unlink(params->lock_filename)) {
1343                 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
1344                 fclose(lockfile);
1345                 meshlink_errno = MESHLINK_ESTORAGE;
1346                 return false;
1347         }
1348
1349         fclose(lockfile);
1350
1351         if(!sync_path(params->confbase)) {
1352                 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
1353                 meshlink_errno = MESHLINK_ESTORAGE;
1354                 return false;
1355         }
1356
1357         return true;
1358 }
1359
1360 bool meshlink_destroy(const char *confbase) {
1361         logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
1362
1363         char lock_filename[PATH_MAX];
1364         snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1365
1366         meshlink_open_params_t params = {
1367                 .confbase = (char *)confbase,
1368                 .lock_filename = lock_filename,
1369         };
1370
1371         return meshlink_destroy_ex(&params);
1372 }
1373
1374 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1375         logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
1376
1377         if(!mesh) {
1378                 meshlink_errno = MESHLINK_EINVAL;
1379                 return;
1380         }
1381
1382         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1383                 abort();
1384         }
1385
1386         mesh->receive_cb = cb;
1387         pthread_mutex_unlock(&mesh->mutex);
1388 }
1389
1390 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1391         logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
1392
1393         if(!mesh) {
1394                 meshlink_errno = MESHLINK_EINVAL;
1395                 return;
1396         }
1397
1398         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1399                 abort();
1400         }
1401
1402         mesh->connection_try_cb = cb;
1403         pthread_mutex_unlock(&mesh->mutex);
1404 }
1405
1406 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1407         logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
1408
1409         if(!mesh) {
1410                 meshlink_errno = MESHLINK_EINVAL;
1411                 return;
1412         }
1413
1414         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1415                 abort();
1416         }
1417
1418         mesh->node_status_cb = cb;
1419         pthread_mutex_unlock(&mesh->mutex);
1420 }
1421
1422 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1423         logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
1424
1425         if(!mesh) {
1426                 meshlink_errno = MESHLINK_EINVAL;
1427                 return;
1428         }
1429
1430         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1431                 abort();
1432         }
1433
1434         mesh->node_duplicate_cb = cb;
1435         pthread_mutex_unlock(&mesh->mutex);
1436 }
1437
1438 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1439         logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
1440
1441         if(mesh) {
1442                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1443                         abort();
1444                 }
1445
1446                 mesh->log_cb = cb;
1447                 mesh->log_level = cb ? level : 0;
1448                 pthread_mutex_unlock(&mesh->mutex);
1449         } else {
1450                 global_log_cb = cb;
1451                 global_log_level = cb ? level : 0;
1452         }
1453 }
1454
1455 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1456         logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
1457
1458         if(!mesh) {
1459                 meshlink_errno = MESHLINK_EINVAL;
1460                 return;
1461         }
1462
1463         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1464                 abort();
1465         }
1466
1467         mesh->error_cb = cb;
1468         pthread_mutex_unlock(&mesh->mutex);
1469 }
1470
1471 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
1472         meshlink_packethdr_t *hdr;
1473
1474         if(len > MAXSIZE - sizeof(*hdr)) {
1475                 meshlink_errno = MESHLINK_EINVAL;
1476                 return false;
1477         }
1478
1479         node_t *n = (node_t *)destination;
1480
1481         if(n->status.blacklisted) {
1482                 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1483                 meshlink_errno = MESHLINK_EBLACKLISTED;
1484                 return false;
1485         }
1486
1487         // Prepare the packet
1488         packet->probe = false;
1489         packet->tcp = false;
1490         packet->len = len + sizeof(*hdr);
1491
1492         hdr = (meshlink_packethdr_t *)packet->data;
1493         memset(hdr, 0, sizeof(*hdr));
1494         // leave the last byte as 0 to make sure strings are always
1495         // null-terminated if they are longer than the buffer
1496         strncpy((char *)hdr->destination, destination->name, sizeof(hdr->destination) - 1);
1497         strncpy((char *)hdr->source, mesh->self->name, sizeof(hdr->source) - 1);
1498
1499         memcpy(packet->data + sizeof(*hdr), data, len);
1500
1501         return true;
1502 }
1503
1504 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1505         assert(mesh);
1506         assert(destination);
1507         assert(data);
1508         assert(len);
1509
1510         // Prepare the packet
1511         if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
1512                 return false;
1513         }
1514
1515         // Send it immediately
1516         route(mesh, mesh->self, mesh->packet);
1517
1518         return true;
1519 }
1520
1521 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1522         logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
1523
1524         // Validate arguments
1525         if(!mesh || !destination) {
1526                 meshlink_errno = MESHLINK_EINVAL;
1527                 return false;
1528         }
1529
1530         if(!len) {
1531                 return true;
1532         }
1533
1534         if(!data) {
1535                 meshlink_errno = MESHLINK_EINVAL;
1536                 return false;
1537         }
1538
1539         // Prepare the packet
1540         vpn_packet_t *packet = malloc(sizeof(*packet));
1541
1542         if(!packet) {
1543                 meshlink_errno = MESHLINK_ENOMEM;
1544                 return false;
1545         }
1546
1547         if(!prepare_packet(mesh, destination, data, len, packet)) {
1548                 free(packet);
1549                 return false;
1550         }
1551
1552         // Queue it
1553         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1554                 free(packet);
1555                 meshlink_errno = MESHLINK_ENOMEM;
1556                 return false;
1557         }
1558
1559         logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
1560
1561         // Notify event loop
1562         signal_trigger(&mesh->loop, &mesh->datafromapp);
1563
1564         return true;
1565 }
1566
1567 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1568         (void)loop;
1569         meshlink_handle_t *mesh = data;
1570
1571         logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
1572
1573         for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1574                 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
1575                 route(mesh, mesh->self, packet);
1576                 free(packet);
1577         }
1578 }
1579
1580 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1581         if(!mesh || !node) {
1582                 meshlink_errno = MESHLINK_EINVAL;
1583                 return NULL;
1584         }
1585
1586         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1587                 abort();
1588         }
1589
1590         node_t *n = (node_t *)node;
1591
1592         if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1593                 meshlink_errno = MESHLINK_EINTERNAL;
1594                 pthread_mutex_unlock(&mesh->mutex);
1595                 return false;
1596         }
1597
1598         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1599
1600         if(!fingerprint) {
1601                 meshlink_errno = MESHLINK_EINTERNAL;
1602         }
1603
1604         pthread_mutex_unlock(&mesh->mutex);
1605         return fingerprint;
1606 }
1607
1608 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1609         if(!mesh) {
1610                 meshlink_errno = MESHLINK_EINVAL;
1611                 return NULL;
1612         }
1613
1614         return (meshlink_node_t *)mesh->self;
1615 }
1616
1617 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1618         if(!mesh || !name) {
1619                 meshlink_errno = MESHLINK_EINVAL;
1620                 return NULL;
1621         }
1622
1623         node_t *n = NULL;
1624
1625         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1626                 abort();
1627         }
1628
1629         n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1630         pthread_mutex_unlock(&mesh->mutex);
1631
1632         if(!n) {
1633                 meshlink_errno = MESHLINK_ENOENT;
1634         }
1635
1636         return (meshlink_node_t *)n;
1637 }
1638
1639 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1640         logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
1641
1642         if(!mesh || !data || !len || !signature || !siglen) {
1643                 meshlink_errno = MESHLINK_EINVAL;
1644                 return false;
1645         }
1646
1647         if(*siglen < MESHLINK_SIGLEN) {
1648                 meshlink_errno = MESHLINK_EINVAL;
1649                 return false;
1650         }
1651
1652         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1653                 abort();
1654         }
1655
1656         if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1657                 meshlink_errno = MESHLINK_EINTERNAL;
1658                 pthread_mutex_unlock(&mesh->mutex);
1659                 return false;
1660         }
1661
1662         *siglen = MESHLINK_SIGLEN;
1663         pthread_mutex_unlock(&mesh->mutex);
1664         return true;
1665 }
1666
1667 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1668         logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
1669
1670         if(!mesh || !source || !data || !len || !signature) {
1671                 meshlink_errno = MESHLINK_EINVAL;
1672                 return false;
1673         }
1674
1675         if(siglen != MESHLINK_SIGLEN) {
1676                 meshlink_errno = MESHLINK_EINVAL;
1677                 return false;
1678         }
1679
1680         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1681                 abort();
1682         }
1683
1684         bool rval = false;
1685
1686         struct node_t *n = (struct node_t *)source;
1687
1688         if(!node_read_public_key(mesh, n)) {
1689                 meshlink_errno = MESHLINK_EINTERNAL;
1690                 rval = false;
1691         } else {
1692                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1693         }
1694
1695         pthread_mutex_unlock(&mesh->mutex);
1696         return rval;
1697 }
1698
1699 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1700         logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
1701
1702         if(!mesh || !node || !address) {
1703                 meshlink_errno = MESHLINK_EINVAL;
1704                 return false;
1705         }
1706
1707         if(!is_valid_hostname(address)) {
1708                 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
1709                 meshlink_errno = MESHLINK_EINVAL;
1710                 return false;
1711         }
1712
1713         if((node_t *)node != mesh->self && !port) {
1714                 logger(mesh, MESHLINK_ERROR, "Missing port number!");
1715                 meshlink_errno = MESHLINK_EINVAL;
1716                 return false;
1717
1718         }
1719
1720         if(port && !is_valid_port(port)) {
1721                 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
1722                 meshlink_errno = MESHLINK_EINVAL;
1723                 return false;
1724         }
1725
1726         char *canonical_address;
1727
1728         xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
1729
1730         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1731                 abort();
1732         }
1733
1734         node_t *n = (node_t *)node;
1735         free(n->canonical_address);
1736         n->canonical_address = canonical_address;
1737
1738         if(!node_write_config(mesh, n, false)) {
1739                 pthread_mutex_unlock(&mesh->mutex);
1740                 return false;
1741         }
1742
1743         pthread_mutex_unlock(&mesh->mutex);
1744
1745         return config_sync(mesh, "current");
1746 }
1747
1748 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
1749         logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
1750
1751         if(!mesh || !node) {
1752                 meshlink_errno = MESHLINK_EINVAL;
1753                 return false;
1754         }
1755
1756         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1757                 abort();
1758         }
1759
1760         node_t *n = (node_t *)node;
1761         free(n->canonical_address);
1762         n->canonical_address = NULL;
1763
1764         if(!node_write_config(mesh, n, false)) {
1765                 pthread_mutex_unlock(&mesh->mutex);
1766                 return false;
1767         }
1768
1769         pthread_mutex_unlock(&mesh->mutex);
1770
1771         return config_sync(mesh, "current");
1772 }
1773
1774 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1775         logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
1776
1777         if(!mesh || !invitation) {
1778                 meshlink_errno = MESHLINK_EINVAL;
1779                 return false;
1780         }
1781
1782         if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
1783                 meshlink_errno = MESHLINK_EINVAL;
1784                 return false;
1785         }
1786
1787         join_state_t state = {
1788                 .mesh = mesh,
1789                 .sock = -1,
1790         };
1791
1792         ecdsa_t *key = NULL;
1793         ecdsa_t *hiskey = NULL;
1794
1795         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1796         char copy[strlen(invitation) + 1];
1797
1798         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1799                 abort();
1800         }
1801
1802         //Before doing meshlink_join make sure we are not connected to another mesh
1803         if(mesh->threadstarted) {
1804                 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
1805                 meshlink_errno = MESHLINK_EINVAL;
1806                 goto exit;
1807         }
1808
1809         // Refuse to join a mesh if we are already part of one. We are part of one if we know at least one other node.
1810         if(mesh->peer) {
1811                 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
1812                 meshlink_errno = MESHLINK_EINVAL;
1813                 goto exit;
1814         }
1815
1816         strcpy(copy, invitation);
1817
1818         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
1819
1820         char *slash = strchr(copy, '/');
1821
1822         if(!slash) {
1823                 goto invalid;
1824         }
1825
1826         *slash++ = 0;
1827
1828         if(strlen(slash) != 48) {
1829                 goto invalid;
1830         }
1831
1832         char *address = copy;
1833         char *port = NULL;
1834
1835         if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
1836                 goto invalid;
1837         }
1838
1839         if(mesh->inviter_commits_first) {
1840                 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
1841         }
1842
1843         // Generate a throw-away key for the invitation.
1844         key = ecdsa_generate();
1845
1846         if(!key) {
1847                 meshlink_errno = MESHLINK_EINTERNAL;
1848                 goto exit;
1849         }
1850
1851         char *b64key = ecdsa_get_base64_public_key(key);
1852         char *comma;
1853
1854         while(address && *address) {
1855                 // We allow commas in the address part to support multiple addresses in one invitation URL.
1856                 comma = strchr(address, ',');
1857
1858                 if(comma) {
1859                         *comma++ = 0;
1860                 }
1861
1862                 // Split of the port
1863                 port = strrchr(address, ':');
1864
1865                 if(!port) {
1866                         goto invalid;
1867                 }
1868
1869                 *port++ = 0;
1870
1871                 // IPv6 address are enclosed in brackets, per RFC 3986
1872                 if(*address == '[') {
1873                         address++;
1874                         char *bracket = strchr(address, ']');
1875
1876                         if(!bracket) {
1877                                 goto invalid;
1878                         }
1879
1880                         *bracket++ = 0;
1881
1882                         if(*bracket) {
1883                                 goto invalid;
1884                         }
1885                 }
1886
1887                 // Connect to the meshlink daemon mentioned in the URL.
1888                 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1889
1890                 if(ai) {
1891                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
1892                                 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
1893
1894                                 if(state.sock == -1) {
1895                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1896                                         meshlink_errno = MESHLINK_ENETWORK;
1897                                         continue;
1898                                 }
1899
1900 #ifdef SO_NOSIGPIPE
1901                                 int nosigpipe = 1;
1902                                 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
1903 #endif
1904
1905                                 set_timeout(state.sock, 5000);
1906
1907                                 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
1908                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1909                                         meshlink_errno = MESHLINK_ENETWORK;
1910                                         closesocket(state.sock);
1911                                         state.sock = -1;
1912                                         continue;
1913                                 }
1914
1915                                 break;
1916                         }
1917
1918                         freeaddrinfo(ai);
1919                 } else {
1920                         meshlink_errno = MESHLINK_ERESOLV;
1921                 }
1922
1923                 if(state.sock != -1 || !comma) {
1924                         break;
1925                 }
1926
1927                 address = comma;
1928         }
1929
1930         if(state.sock == -1) {
1931                 goto exit;
1932         }
1933
1934         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1935
1936         // Tell him we have an invitation, and give him our throw-away key.
1937
1938         state.blen = 0;
1939
1940         if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
1941                 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1942                 meshlink_errno = MESHLINK_ENETWORK;
1943                 goto exit;
1944         }
1945
1946         free(b64key);
1947
1948         char hisname[4096] = "";
1949         int code, hismajor, hisminor = 0;
1950
1951         if(!recvline(&state) || sscanf(state.line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(&state) || !rstrip(state.line) || sscanf(state.line, "%d ", &code) != 1 || code != ACK || strlen(state.line) < 3) {
1952                 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
1953                 meshlink_errno = MESHLINK_ENETWORK;
1954                 goto exit;
1955         }
1956
1957         // Check if the hash of the key he gave us matches the hash in the URL.
1958         char *fingerprint = state.line + 2;
1959         char hishash[64];
1960
1961         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1962                 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
1963                 meshlink_errno = MESHLINK_EINTERNAL;
1964                 goto exit;
1965         }
1966
1967         if(memcmp(hishash, state.hash, 18)) {
1968                 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
1969                 meshlink_errno = MESHLINK_EPEER;
1970                 goto exit;
1971         }
1972
1973         hiskey = ecdsa_set_base64_public_key(fingerprint);
1974
1975         if(!hiskey) {
1976                 meshlink_errno = MESHLINK_EINTERNAL;
1977                 goto exit;
1978         }
1979
1980         // Start an SPTPS session
1981         if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
1982                 meshlink_errno = MESHLINK_EINTERNAL;
1983                 goto exit;
1984         }
1985
1986         // Feed rest of input buffer to SPTPS
1987         if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
1988                 meshlink_errno = MESHLINK_EPEER;
1989                 goto exit;
1990         }
1991
1992         ssize_t len;
1993         logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
1994
1995         while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
1996                 if(len < 0) {
1997                         if(errno == EINTR) {
1998                                 continue;
1999                         }
2000
2001                         logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2002                         meshlink_errno = MESHLINK_ENETWORK;
2003                         goto exit;
2004                 }
2005
2006                 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2007                         meshlink_errno = MESHLINK_EPEER;
2008                         goto exit;
2009                 }
2010         }
2011
2012         if(!state.success) {
2013                 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
2014                 meshlink_errno = MESHLINK_EPEER;
2015                 goto exit;
2016         }
2017
2018         sptps_stop(&state.sptps);
2019         ecdsa_free(hiskey);
2020         ecdsa_free(key);
2021         closesocket(state.sock);
2022
2023         pthread_mutex_unlock(&mesh->mutex);
2024         return true;
2025
2026 invalid:
2027         logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
2028         meshlink_errno = MESHLINK_EINVAL;
2029 exit:
2030         sptps_stop(&state.sptps);
2031         ecdsa_free(hiskey);
2032         ecdsa_free(key);
2033
2034         if(state.sock != -1) {
2035                 closesocket(state.sock);
2036         }
2037
2038         pthread_mutex_unlock(&mesh->mutex);
2039         return false;
2040 }
2041
2042 char *meshlink_export(meshlink_handle_t *mesh) {
2043         if(!mesh) {
2044                 meshlink_errno = MESHLINK_EINVAL;
2045                 return NULL;
2046         }
2047
2048         // Create a config file on the fly.
2049
2050         uint8_t buf[4096];
2051         packmsg_output_t out = {buf, sizeof(buf)};
2052         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2053         packmsg_add_str(&out, mesh->name);
2054         packmsg_add_str(&out, CORE_MESH);
2055
2056         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2057                 abort();
2058         }
2059
2060         packmsg_add_int32(&out, mesh->self->devclass);
2061         packmsg_add_bool(&out, mesh->self->status.blacklisted);
2062         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2063
2064         if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
2065                 char *canonical_address = NULL;
2066                 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
2067                 packmsg_add_str(&out, canonical_address);
2068                 free(canonical_address);
2069         } else {
2070                 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2071         }
2072
2073         uint32_t count = 0;
2074
2075         for(uint32_t i = 0; i < MAX_RECENT; i++) {
2076                 if(mesh->self->recent[i].sa.sa_family) {
2077                         count++;
2078                 } else {
2079                         break;
2080                 }
2081         }
2082
2083         packmsg_add_array(&out, count);
2084
2085         for(uint32_t i = 0; i < count; i++) {
2086                 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2087         }
2088
2089         packmsg_add_int64(&out, 0);
2090         packmsg_add_int64(&out, 0);
2091
2092         pthread_mutex_unlock(&mesh->mutex);
2093
2094         if(!packmsg_output_ok(&out)) {
2095                 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2096                 meshlink_errno = MESHLINK_EINTERNAL;
2097                 return NULL;
2098         }
2099
2100         // Prepare a base64-encoded packmsg array containing our config file
2101
2102         uint32_t len = packmsg_output_size(&out, buf);
2103         uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2104         uint8_t *buf2 = xmalloc(len2);
2105         packmsg_output_t out2 = {buf2, len2};
2106         packmsg_add_array(&out2, 1);
2107         packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2108
2109         if(!packmsg_output_ok(&out2)) {
2110                 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2111                 meshlink_errno = MESHLINK_EINTERNAL;
2112                 free(buf2);
2113                 return NULL;
2114         }
2115
2116         b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2117
2118         return (char *)buf2;
2119 }
2120
2121 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2122         logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
2123
2124         if(!mesh || !data) {
2125                 meshlink_errno = MESHLINK_EINVAL;
2126                 return false;
2127         }
2128
2129         size_t datalen = strlen(data);
2130         uint8_t *buf = xmalloc(datalen);
2131         int buflen = b64decode(data, buf, datalen);
2132
2133         if(!buflen) {
2134                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2135                 free(buf);
2136                 meshlink_errno = MESHLINK_EPEER;
2137                 return false;
2138         }
2139
2140         packmsg_input_t in = {buf, buflen};
2141         uint32_t count = packmsg_get_array(&in);
2142
2143         if(!count) {
2144                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2145                 free(buf);
2146                 meshlink_errno = MESHLINK_EPEER;
2147                 return false;
2148         }
2149
2150         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2151                 abort();
2152         }
2153
2154         while(count--) {
2155                 const void *data2;
2156                 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
2157
2158                 if(!len2) {
2159                         break;
2160                 }
2161
2162                 packmsg_input_t in2 = {data2, len2};
2163                 uint32_t version = packmsg_get_uint32(&in2);
2164                 char *name = packmsg_get_str_dup(&in2);
2165
2166                 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2167                         free(name);
2168                         packmsg_input_invalidate(&in);
2169                         break;
2170                 }
2171
2172                 if(!check_id(name)) {
2173                         free(name);
2174                         break;
2175                 }
2176
2177                 node_t *n = lookup_node(mesh, name);
2178
2179                 if(n) {
2180                         logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2181                         free(name);
2182                         continue;
2183                 }
2184
2185                 n = new_node();
2186                 n->name = name;
2187
2188                 config_t config = {data2, len2};
2189
2190                 if(!node_read_from_config(mesh, n, &config)) {
2191                         free_node(n);
2192                         packmsg_input_invalidate(&in);
2193                         break;
2194                 }
2195
2196                 if(!node_write_config(mesh, n, true)) {
2197                         free_node(n);
2198                         free(buf);
2199                         return false;
2200                 }
2201
2202                 node_add(mesh, n);
2203         }
2204
2205         pthread_mutex_unlock(&mesh->mutex);
2206
2207         free(buf);
2208
2209         if(!packmsg_done(&in)) {
2210                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2211                 meshlink_errno = MESHLINK_EPEER;
2212                 return false;
2213         }
2214
2215         if(!config_sync(mesh, "current")) {
2216                 return false;
2217         }
2218
2219         return true;
2220 }
2221
2222 /* Hint that a hostname may be found at an address
2223  * See header file for detailed comment.
2224  */
2225 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2226         logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
2227
2228         if(!mesh || !node || !addr) {
2229                 meshlink_errno = EINVAL;
2230                 return;
2231         }
2232
2233         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2234                 abort();
2235         }
2236
2237         node_t *n = (node_t *)node;
2238
2239         if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
2240                 if(!node_write_config(mesh, n, false)) {
2241                         logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
2242                 }
2243         }
2244
2245         pthread_mutex_unlock(&mesh->mutex);
2246         // @TODO do we want to fire off a connection attempt right away?
2247 }
2248
2249 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2250         (void)port;
2251         node_t *n = utcp->priv;
2252         meshlink_handle_t *mesh = n->mesh;
2253
2254         if(mesh->channel_accept_cb && mesh->channel_listen_cb) {
2255                 return mesh->channel_listen_cb(mesh, (meshlink_node_t *)n, port);
2256         } else {
2257                 return mesh->channel_accept_cb;
2258         }
2259 }
2260
2261 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2262         meshlink_channel_t *channel = connection->priv;
2263
2264         if(!channel) {
2265                 abort();
2266         }
2267
2268         node_t *n = channel->node;
2269         meshlink_handle_t *mesh = n->mesh;
2270
2271         if(n->status.destroyed) {
2272                 meshlink_channel_close(mesh, channel);
2273                 return len;
2274         }
2275
2276         const char *p = data;
2277         size_t left = len;
2278
2279         if(channel->receive_cb) {
2280                 channel->receive_cb(mesh, channel, p, left);
2281         }
2282
2283         return len;
2284 }
2285
2286 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2287         node_t *n = utcp_connection->utcp->priv;
2288
2289         if(!n) {
2290                 abort();
2291         }
2292
2293         meshlink_handle_t *mesh = n->mesh;
2294
2295         if(!mesh->channel_accept_cb) {
2296                 return;
2297         }
2298
2299         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2300         channel->node = n;
2301         channel->c = utcp_connection;
2302
2303         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2304                 utcp_accept(utcp_connection, channel_recv, channel);
2305         } else {
2306                 free(channel);
2307         }
2308 }
2309
2310 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2311         node_t *n = utcp->priv;
2312
2313         if(n->status.destroyed) {
2314                 return -1;
2315         }
2316
2317         meshlink_handle_t *mesh = n->mesh;
2318         return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2319 }
2320
2321 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2322         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_receive_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
2323
2324         if(!mesh || !channel) {
2325                 meshlink_errno = MESHLINK_EINVAL;
2326                 return;
2327         }
2328
2329         channel->receive_cb = cb;
2330 }
2331
2332 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2333         (void)mesh;
2334         node_t *n = (node_t *)source;
2335
2336         if(!n->utcp) {
2337                 abort();
2338         }
2339
2340         utcp_recv(n->utcp, data, len);
2341 }
2342
2343 void meshlink_set_channel_listen_cb(meshlink_handle_t *mesh, meshlink_channel_listen_cb_t cb) {
2344         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_listen_cb(%p)", (void *)(intptr_t)cb);
2345
2346         if(!mesh) {
2347                 meshlink_errno = MESHLINK_EINVAL;
2348                 return;
2349         }
2350
2351         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2352                 abort();
2353         }
2354
2355         mesh->channel_listen_cb = cb;
2356
2357         pthread_mutex_unlock(&mesh->mutex);
2358 }
2359
2360 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2361         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_accept_cb(%p)", (void *)(intptr_t)cb);
2362
2363         if(!mesh) {
2364                 meshlink_errno = MESHLINK_EINVAL;
2365                 return;
2366         }
2367
2368         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2369                 abort();
2370         }
2371
2372         mesh->channel_accept_cb = cb;
2373         mesh->receive_cb = channel_receive;
2374
2375         if(mesh->peer) {
2376                 mesh->peer->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, mesh->peer);
2377         }
2378
2379         pthread_mutex_unlock(&mesh->mutex);
2380 }
2381
2382 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
2383         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf(%p, %zu)", (void *)channel, size);
2384
2385         meshlink_set_channel_sndbuf_storage(mesh, channel, NULL, size);
2386 }
2387
2388 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
2389         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf(%p, %zu)", (void *)channel, size);
2390
2391         meshlink_set_channel_rcvbuf_storage(mesh, channel, NULL, size);
2392 }
2393
2394 void meshlink_set_channel_sndbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
2395         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
2396
2397         if(!mesh || !channel) {
2398                 meshlink_errno = MESHLINK_EINVAL;
2399                 return;
2400         }
2401
2402         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2403                 abort();
2404         }
2405
2406         utcp_set_sndbuf(channel->c, buf, size);
2407         pthread_mutex_unlock(&mesh->mutex);
2408 }
2409
2410 void meshlink_set_channel_rcvbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
2411         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
2412
2413         if(!mesh || !channel) {
2414                 meshlink_errno = MESHLINK_EINVAL;
2415                 return;
2416         }
2417
2418         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2419                 abort();
2420         }
2421
2422         utcp_set_rcvbuf(channel->c, buf, size);
2423         pthread_mutex_unlock(&mesh->mutex);
2424 }
2425
2426 void meshlink_set_channel_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint32_t flags) {
2427         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_flags(%p, %u)", (void *)channel, flags);
2428
2429         if(!mesh || !channel) {
2430                 meshlink_errno = MESHLINK_EINVAL;
2431                 return;
2432         }
2433
2434         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2435                 abort();
2436         }
2437
2438         utcp_set_flags(channel->c, flags);
2439         pthread_mutex_unlock(&mesh->mutex);
2440 }
2441
2442 meshlink_channel_t *meshlink_channel_open_ex(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len, uint32_t flags) {
2443         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu, %u)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len, flags);
2444
2445         if(data && len) {
2446                 abort();        // TODO: handle non-NULL data
2447         }
2448
2449         if(!mesh || !node) {
2450                 meshlink_errno = MESHLINK_EINVAL;
2451                 return NULL;
2452         }
2453
2454         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2455                 abort();
2456         }
2457
2458         node_t *n = (node_t *)node;
2459
2460         if(!n->utcp) {
2461                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2462                 mesh->receive_cb = channel_receive;
2463
2464                 if(!n->utcp) {
2465                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2466                         pthread_mutex_unlock(&mesh->mutex);
2467                         return NULL;
2468                 }
2469         }
2470
2471         if(n->status.blacklisted) {
2472                 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
2473                 meshlink_errno = MESHLINK_EBLACKLISTED;
2474                 pthread_mutex_unlock(&mesh->mutex);
2475                 return NULL;
2476         }
2477
2478         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2479         channel->node = n;
2480         channel->receive_cb = cb;
2481
2482         if(data && !len) {
2483                 channel->priv = (void *)data;
2484         }
2485
2486         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2487
2488         pthread_mutex_unlock(&mesh->mutex);
2489
2490         if(!channel->c) {
2491                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2492                 free(channel);
2493                 return NULL;
2494         }
2495
2496         return channel;
2497 }
2498
2499 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) {
2500         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len);
2501
2502         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2503 }
2504
2505 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2506         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_shutdown(%p, %d)", (void *)channel, direction);
2507
2508         if(!mesh || !channel) {
2509                 meshlink_errno = MESHLINK_EINVAL;
2510                 return;
2511         }
2512
2513         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2514                 abort();
2515         }
2516
2517         utcp_shutdown(channel->c, direction);
2518         pthread_mutex_unlock(&mesh->mutex);
2519 }
2520
2521 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2522         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_close(%p)", (void *)channel);
2523
2524         if(!mesh || !channel) {
2525                 meshlink_errno = MESHLINK_EINVAL;
2526                 return;
2527         }
2528
2529         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2530                 abort();
2531         }
2532
2533         if(channel->c) {
2534                 utcp_close(channel->c);
2535                 channel->c = NULL;
2536         }
2537
2538         if(!channel->in_callback) {
2539                 free(channel);
2540         }
2541
2542         pthread_mutex_unlock(&mesh->mutex);
2543 }
2544
2545 void meshlink_channel_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2546         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_abort(%p)", (void *)channel);
2547
2548         if(!mesh || !channel) {
2549                 meshlink_errno = MESHLINK_EINVAL;
2550                 return;
2551         }
2552
2553         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2554                 abort();
2555         }
2556
2557         if(channel->c) {
2558                 utcp_abort(channel->c);
2559                 channel->c = NULL;
2560         }
2561
2562         if(!channel->in_callback) {
2563                 free(channel);
2564         }
2565
2566         pthread_mutex_unlock(&mesh->mutex);
2567 }
2568
2569 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2570         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_send(%p, %p, %zu)", (void *)channel, data, len);
2571
2572         if(!mesh || !channel) {
2573                 meshlink_errno = MESHLINK_EINVAL;
2574                 return -1;
2575         }
2576
2577         if(!len) {
2578                 return 0;
2579         }
2580
2581         if(!data) {
2582                 meshlink_errno = MESHLINK_EINVAL;
2583                 return -1;
2584         }
2585
2586         // TODO: more finegrained locking.
2587         // Ideally we want to put the data into the UTCP connection's send buffer.
2588         // Then, preferably only if there is room in the receiver window,
2589         // kick the meshlink thread to go send packets.
2590
2591         ssize_t retval;
2592
2593         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2594                 abort();
2595         }
2596
2597         retval = utcp_send(channel->c, data, len);
2598
2599         pthread_mutex_unlock(&mesh->mutex);
2600
2601         if(retval < 0) {
2602                 meshlink_errno = MESHLINK_ENETWORK;
2603         }
2604
2605         return retval;
2606 }
2607
2608 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2609         if(!mesh || !channel) {
2610                 meshlink_errno = MESHLINK_EINVAL;
2611                 return -1;
2612         }
2613
2614         return channel->c->flags;
2615 }
2616
2617 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2618         if(!mesh || !channel) {
2619                 meshlink_errno = MESHLINK_EINVAL;
2620                 return -1;
2621         }
2622
2623         return utcp_get_sendq(channel->c);
2624 }
2625
2626 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2627         if(!mesh || !channel) {
2628                 meshlink_errno = MESHLINK_EINVAL;
2629                 return -1;
2630         }
2631
2632         return utcp_get_recvq(channel->c);
2633 }
2634
2635 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2636         if(!mesh || !channel) {
2637                 meshlink_errno = MESHLINK_EINVAL;
2638                 return -1;
2639         }
2640
2641         return utcp_get_mss(channel->node->utcp);
2642 }
2643
2644 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
2645         logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_channel_timeout(%s, %d)", node ? node->name : "(null)", timeout);
2646
2647         if(!mesh || !node) {
2648                 meshlink_errno = MESHLINK_EINVAL;
2649                 return;
2650         }
2651
2652         node_t *n = (node_t *)node;
2653
2654         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2655                 abort();
2656         }
2657
2658         if(!n->utcp) {
2659                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2660         }
2661
2662         utcp_set_user_timeout(n->utcp, timeout);
2663
2664         pthread_mutex_unlock(&mesh->mutex);
2665 }
2666
2667 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2668         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2669                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2670         }
2671
2672         if(mesh->node_status_cb) {
2673                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
2674         }
2675 }
2676
2677 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2678         if(!mesh->node_duplicate_cb || n->status.duplicate) {
2679                 return;
2680         }
2681
2682         n->status.duplicate = true;
2683         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2684 }
2685
2686 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
2687         logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
2688
2689         if(!mesh) {
2690                 meshlink_errno = MESHLINK_EINVAL;
2691                 return;
2692         }
2693
2694         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2695                 abort();
2696         }
2697
2698         pthread_mutex_unlock(&mesh->mutex);
2699 }
2700
2701 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
2702         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
2703
2704         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2705                 meshlink_errno = EINVAL;
2706                 return;
2707         }
2708
2709         if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
2710                 meshlink_errno = EINVAL;
2711                 return;
2712         }
2713
2714         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2715                 abort();
2716         }
2717
2718         mesh->dev_class_traits[devclass].pinginterval = pinginterval;
2719         mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
2720         pthread_mutex_unlock(&mesh->mutex);
2721 }
2722
2723 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
2724         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
2725
2726         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2727                 meshlink_errno = EINVAL;
2728                 return;
2729         }
2730
2731         if(fast_retry_period < 0) {
2732                 meshlink_errno = EINVAL;
2733                 return;
2734         }
2735
2736         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2737                 abort();
2738         }
2739
2740         mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
2741         pthread_mutex_unlock(&mesh->mutex);
2742 }
2743
2744 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
2745         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
2746
2747         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2748                 meshlink_errno = EINVAL;
2749                 return;
2750         }
2751
2752         if(maxtimeout < 0) {
2753                 meshlink_errno = EINVAL;
2754                 return;
2755         }
2756
2757         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2758                 abort();
2759         }
2760
2761         mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
2762         pthread_mutex_unlock(&mesh->mutex);
2763 }
2764
2765 void meshlink_reset_timers(struct meshlink_handle *mesh) {
2766         logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
2767
2768         if(!mesh) {
2769                 return;
2770         }
2771
2772         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2773                 abort();
2774         }
2775
2776         handle_network_change(mesh, true);
2777
2778         pthread_mutex_unlock(&mesh->mutex);
2779 }
2780
2781 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
2782         logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
2783
2784         if(!mesh) {
2785                 meshlink_errno = EINVAL;
2786                 return;
2787         }
2788
2789         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2790                 abort();
2791         }
2792
2793         mesh->inviter_commits_first = inviter_commits_first;
2794         pthread_mutex_unlock(&mesh->mutex);
2795 }
2796
2797 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
2798         logger(mesh, MESHLINK_DEBUG, "meshlink_set_scheduling_granularity(%ld)", granularity);
2799
2800         if(!mesh || granularity < 0) {
2801                 meshlink_errno = EINVAL;
2802                 return;
2803         }
2804
2805         utcp_set_clock_granularity(granularity);
2806 }
2807
2808 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
2809         logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
2810
2811         if(!mesh) {
2812                 meshlink_errno = EINVAL;
2813                 return;
2814         }
2815
2816         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2817                 abort();
2818         }
2819
2820         mesh->storage_policy = policy;
2821         pthread_mutex_unlock(&mesh->mutex);
2822 }
2823
2824 void handle_network_change(meshlink_handle_t *mesh, bool online) {
2825         (void)online;
2826
2827         if(!mesh->loop.running) {
2828                 return;
2829         }
2830
2831         retry(mesh);
2832         signal_trigger(&mesh->loop, &mesh->datafromapp);
2833 }
2834
2835 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
2836         // We should only call the callback function if we are in the background thread.
2837         if(!mesh->error_cb) {
2838                 return;
2839         }
2840
2841         if(!mesh->threadstarted) {
2842                 return;
2843         }
2844
2845         if(mesh->thread == pthread_self()) {
2846                 mesh->error_cb(mesh, cb_errno);
2847         }
2848 }
2849
2850 static void __attribute__((constructor)) meshlink_init(void) {
2851         crypto_init();
2852         utcp_set_clock_granularity(10000);
2853 }
2854
2855 static void __attribute__((destructor)) meshlink_exit(void) {
2856         crypto_exit();
2857 }