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