]> git.meshlink.io Git - meshlink/blob - src/discovery.c
5687cc351c50488ae940c34746e63a1a41c57ceb
[meshlink] / src / discovery.c
1 #include "system.h"
2
3 #include <catta/core.h>
4 #include <catta/lookup.h>
5 #include <catta/publish.h>
6 #include <catta/log.h>
7 #include <catta/simple-watch.h>
8 #include <catta/malloc.h>
9 #include <catta/alternative.h>
10 #include <catta/error.h>
11
12 #if defined(__APPLE__) || defined(__unix) && !defined(__linux)
13 #include <net/route.h>
14 #elif defined(__linux)
15 #include <asm/types.h>
16 #include <linux/netlink.h>
17 #include <linux/rtnetlink.h>
18 #endif
19
20 #include "meshlink_internal.h"
21 #include "event.h"
22 #include "discovery.h"
23 #include "sockaddr.h"
24 #include "logger.h"
25 #include "node.h"
26 #include "connection.h"
27 #include "xalloc.h"
28
29 #define MESHLINK_MDNS_SERVICE_TYPE "_%s._tcp"
30 #define MESHLINK_MDNS_NAME_KEY "name"
31 #define MESHLINK_MDNS_FINGERPRINT_KEY "fingerprint"
32
33 static void generate_rand_string(meshlink_handle_t *mesh, char *buffer, size_t size) {
34         assert(size);
35
36         for(size_t i = 0; i < (size - 1); ++i) {
37                 buffer[i] = 'a' + prng(mesh, 'z' - 'a' + 1);
38         }
39
40         buffer[size - 1] = '\0';
41 }
42
43 static void discovery_entry_group_callback(CattaServer *server, CattaSEntryGroup *group, CattaEntryGroupState state, void *userdata) {
44         (void)server;
45         (void)group;
46         meshlink_handle_t *mesh = userdata;
47
48         assert(mesh);
49         assert(mesh->catta_server);
50         assert(mesh->catta_poll);
51
52         /* Called whenever the entry group state changes */
53         switch(state) {
54         case CATTA_ENTRY_GROUP_ESTABLISHED:
55                 /* The entry group has been established successfully */
56                 logger(mesh, MESHLINK_DEBUG, "Catta Service successfully established.\n");
57                 break;
58
59         case CATTA_ENTRY_GROUP_COLLISION:
60                 logger(mesh, MESHLINK_WARNING, "Catta Service collision.\n");
61                 // @TODO can we just set a new name and retry?
62                 break;
63
64         case CATTA_ENTRY_GROUP_FAILURE :
65                 /* Some kind of failure happened while we were registering our services */
66                 logger(mesh, MESHLINK_ERROR, "Catta Entry group failure: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
67                 catta_simple_poll_quit(mesh->catta_poll);
68                 break;
69
70         case CATTA_ENTRY_GROUP_UNCOMMITED:
71         case CATTA_ENTRY_GROUP_REGISTERING:
72                 break;
73         }
74 }
75
76
77 static void discovery_create_services(meshlink_handle_t *mesh) {
78         char *fingerprint = NULL;
79         char *txt_name = NULL;
80         char *txt_fingerprint = NULL;
81
82         assert(mesh);
83         assert(mesh->name);
84         assert(mesh->myport);
85         assert(mesh->catta_server);
86         assert(mesh->catta_poll);
87         assert(mesh->catta_servicetype);
88         assert(mesh->self);
89
90         logger(mesh, MESHLINK_DEBUG, "Adding service\n");
91
92         /* Ifthis is the first time we're called, let's create a new entry group */
93         if(!(mesh->catta_group = catta_s_entry_group_new(mesh->catta_server, discovery_entry_group_callback, mesh))) {
94                 logger(mesh, MESHLINK_ERROR, "catta_entry_group_new() failed: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
95                 goto fail;
96         }
97
98         /* Create txt records */
99         fingerprint = meshlink_get_fingerprint(mesh, (meshlink_node_t *)mesh->self);
100         xasprintf(&txt_name, "%s=%s", MESHLINK_MDNS_NAME_KEY, mesh->name);
101         xasprintf(&txt_fingerprint, "%s=%s", MESHLINK_MDNS_FINGERPRINT_KEY, fingerprint);
102
103         /* Add the service */
104         int ret = 0;
105
106         if((ret = catta_server_add_service(mesh->catta_server, mesh->catta_group, CATTA_IF_UNSPEC, CATTA_PROTO_UNSPEC, 0, fingerprint, mesh->catta_servicetype, NULL, NULL, atoi(mesh->myport), txt_name, txt_fingerprint, NULL)) < 0) {
107                 logger(mesh, MESHLINK_ERROR, "Failed to add service: %s\n", catta_strerror(ret));
108                 goto fail;
109         }
110
111         /* Tell the server to register the service */
112         if((ret = catta_s_entry_group_commit(mesh->catta_group)) < 0) {
113                 logger(mesh, MESHLINK_ERROR, "Failed to commit entry_group: %s\n", catta_strerror(ret));
114                 goto fail;
115         }
116
117         goto done;
118
119 fail:
120         catta_simple_poll_quit(mesh->catta_poll);
121
122 done:
123         free(fingerprint);
124         free(txt_name);
125         free(txt_fingerprint);
126 }
127
128 static void discovery_server_callback(CattaServer *server, CattaServerState state, void *userdata) {
129         (void)server;
130         meshlink_handle_t *mesh = userdata;
131
132         assert(mesh);
133
134         switch(state) {
135         case CATTA_SERVER_RUNNING:
136
137                 /* The serve has startup successfully and registered its host
138                  * name on the network, so it's time to create our services */
139                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
140                         abort();
141                 }
142
143                 if(!mesh->catta_group) {
144                         discovery_create_services(mesh);
145                 }
146
147                 pthread_mutex_unlock(&mesh->mutex);
148
149                 break;
150
151         case CATTA_SERVER_COLLISION: {
152                 /* A host name collision happened. Let's pick a new name for the server */
153                 char hostname[17];
154                 generate_rand_string(mesh, hostname, sizeof(hostname));
155
156                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
157                         abort();
158                 }
159
160                 assert(mesh->catta_server);
161                 assert(mesh->catta_poll);
162
163                 int result = catta_server_set_host_name(mesh->catta_server, hostname);
164
165                 if(result < 0) {
166                         catta_simple_poll_quit(mesh->catta_poll);
167                 }
168
169                 pthread_mutex_unlock(&mesh->mutex);
170         }
171         break;
172
173         case CATTA_SERVER_REGISTERING:
174                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
175                         abort();
176                 }
177
178                 /* Let's drop our registered services. When the server is back
179                  * in CATTA_SERVER_RUNNING state we will register them
180                  * again with the new host name. */
181                 if(mesh->catta_group) {
182                         catta_s_entry_group_reset(mesh->catta_group);
183                         mesh->catta_group = NULL;
184                 }
185
186                 pthread_mutex_unlock(&mesh->mutex);
187
188                 break;
189
190         case CATTA_SERVER_FAILURE:
191                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
192                         abort();
193                 }
194
195                 assert(mesh->catta_server);
196                 assert(mesh->catta_poll);
197
198                 /* Terminate on failure */
199                 catta_simple_poll_quit(mesh->catta_poll);
200
201                 pthread_mutex_unlock(&mesh->mutex);
202                 break;
203
204         case CATTA_SERVER_INVALID:
205                 break;
206         }
207 }
208
209 static void discovery_resolve_callback(CattaSServiceResolver *resolver, CattaIfIndex interface_, CattaProtocol protocol, CattaResolverEvent event, const char *name, const char *type, const char *domain, const char *host_name, const CattaAddress *address, uint16_t port, CattaStringList *txt, CattaLookupResultFlags flags, void *userdata) {
210         (void)interface_;
211         (void)protocol;
212         (void)flags;
213         (void)name;
214         (void)type;
215         (void)domain;
216         (void)host_name;
217
218         meshlink_handle_t *mesh = userdata;
219
220         assert(mesh);
221
222         if(event != CATTA_RESOLVER_FOUND) {
223                 catta_s_service_resolver_free(resolver);
224                 return;
225         }
226
227         // retrieve fingerprint
228         CattaStringList *node_name_li = catta_string_list_find(txt, MESHLINK_MDNS_NAME_KEY);
229         CattaStringList *node_fp_li = catta_string_list_find(txt, MESHLINK_MDNS_FINGERPRINT_KEY);
230
231         if(node_name_li && node_fp_li) {
232                 char *node_name = (char *)catta_string_list_get_text(node_name_li) + strlen(MESHLINK_MDNS_NAME_KEY);
233                 char *node_fp = (char *)catta_string_list_get_text(node_fp_li) + strlen(MESHLINK_MDNS_FINGERPRINT_KEY);
234
235                 if(node_name[0] == '=' && node_fp[0] == '=') {
236                         if(pthread_mutex_lock(&mesh->mutex) != 0) {
237                                 abort();
238                         }
239
240                         node_name += 1;
241
242                         meshlink_node_t *node = meshlink_get_node(mesh, node_name);
243
244                         if(node) {
245                                 logger(mesh, MESHLINK_INFO, "Node %s is part of the mesh network.\n", node->name);
246
247                                 sockaddr_t naddress;
248                                 memset(&naddress, 0, sizeof(naddress));
249
250                                 switch(address->proto) {
251                                 case CATTA_PROTO_INET: {
252                                         naddress.in.sin_family = AF_INET;
253                                         naddress.in.sin_port = htons(port);
254                                         naddress.in.sin_addr.s_addr = address->data.ipv4.address;
255                                 }
256                                 break;
257
258                                 case CATTA_PROTO_INET6: {
259                                         naddress.in6.sin6_family = AF_INET6;
260                                         naddress.in6.sin6_port = htons(port);
261                                         memcpy(naddress.in6.sin6_addr.s6_addr, address->data.ipv6.address, sizeof(naddress.in6.sin6_addr.s6_addr));
262                                 }
263                                 break;
264
265                                 default:
266                                         naddress.unknown.family = AF_UNKNOWN;
267                                         break;
268                                 }
269
270                                 if(naddress.unknown.family != AF_UNKNOWN) {
271                                         node_t *n = (node_t *)node;
272                                         connection_t *c = n->connection;
273
274                                         n->catta_address = naddress;
275                                         node_add_recent_address(mesh, n, &naddress);
276
277                                         if(c && c->outgoing && !c->status.active) {
278                                                 c->outgoing->timeout = 0;
279
280                                                 if(c->outgoing->ev.cb) {
281                                                         timeout_set(&mesh->loop, &c->outgoing->ev, &(struct timespec) {
282                                                                 0, 0
283                                                         });
284                                                 }
285
286                                                 c->last_ping_time = -3600;
287                                         }
288
289                                 } else {
290                                         logger(mesh, MESHLINK_WARNING, "Could not resolve node %s to a known address family type.\n", node->name);
291                                 }
292                         } else {
293                                 logger(mesh, MESHLINK_WARNING, "Node %s is not part of the mesh network.\n", node_name);
294                         }
295
296                         pthread_mutex_unlock(&mesh->mutex);
297                 }
298         }
299
300         catta_s_service_resolver_free(resolver);
301 }
302
303 static void discovery_browse_callback(CattaSServiceBrowser *browser, CattaIfIndex interface_, CattaProtocol protocol, CattaBrowserEvent event, const char *name, const char *type, const char *domain, CattaLookupResultFlags flags, void *userdata) {
304         (void)browser;
305         (void)flags;
306         meshlink_handle_t *mesh = userdata;
307
308         /* Called whenever a new services becomes available on the LAN or is removed from the LAN */
309         switch(event) {
310         case CATTA_BROWSER_FAILURE:
311                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
312                         abort();
313                 }
314
315                 catta_simple_poll_quit(mesh->catta_poll);
316                 pthread_mutex_unlock(&mesh->mutex);
317                 break;
318
319         case CATTA_BROWSER_NEW:
320                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
321                         abort();
322                 }
323
324                 catta_s_service_resolver_new(mesh->catta_server, interface_, protocol, name, type, domain, CATTA_PROTO_UNSPEC, 0, discovery_resolve_callback, mesh);
325                 handle_network_change(mesh, ++mesh->catta_interfaces);
326                 pthread_mutex_unlock(&mesh->mutex);
327                 break;
328
329         case CATTA_BROWSER_REMOVE:
330                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
331                         abort();
332                 }
333
334                 handle_network_change(mesh, --mesh->catta_interfaces);
335                 pthread_mutex_unlock(&mesh->mutex);
336                 break;
337
338         case CATTA_BROWSER_ALL_FOR_NOW:
339         case CATTA_BROWSER_CACHE_EXHAUSTED:
340                 break;
341         }
342 }
343
344 static void discovery_log_cb(CattaLogLevel level, const char *txt) {
345         meshlink_log_level_t mlevel = MESHLINK_CRITICAL;
346
347         switch(level) {
348         case CATTA_LOG_ERROR:
349                 mlevel = MESHLINK_ERROR;
350                 break;
351
352         case CATTA_LOG_WARN:
353                 mlevel = MESHLINK_WARNING;
354                 break;
355
356         case CATTA_LOG_NOTICE:
357         case CATTA_LOG_INFO:
358                 mlevel = MESHLINK_INFO;
359                 break;
360
361         case CATTA_LOG_DEBUG:
362         default:
363                 mlevel = MESHLINK_DEBUG;
364                 break;
365         }
366
367         logger(NULL, mlevel, "%s\n", txt);
368 }
369
370 static void *discovery_loop(void *userdata) {
371         bool status = false;
372         meshlink_handle_t *mesh = userdata;
373         assert(mesh);
374
375         if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
376                 abort();
377         }
378
379         // handle catta logs
380         catta_set_log_function(discovery_log_cb);
381
382         // create service type string
383         char appname[strlen(mesh->appname) + 2];
384         strcpy(appname, mesh->appname);
385
386         for(char *p = appname; *p; p++) {
387                 if(!isalnum(*p) && *p != '_' && *p != '-') {
388                         *p = '_';
389                 }
390         }
391
392         if(!appname[1]) {
393                 appname[1] = '_';
394                 appname[2] = '\0';
395         }
396
397         size_t servicetype_strlen = sizeof(MESHLINK_MDNS_SERVICE_TYPE) + strlen(appname) + 1;
398         mesh->catta_servicetype = malloc(servicetype_strlen);
399
400         if(mesh->catta_servicetype == NULL) {
401                 logger(mesh, MESHLINK_ERROR, "Failed to allocate memory for service type string.\n");
402                 goto fail;
403         }
404
405         snprintf(mesh->catta_servicetype, servicetype_strlen, MESHLINK_MDNS_SERVICE_TYPE, appname);
406
407         // Allocate discovery loop object
408         if(!(mesh->catta_poll = catta_simple_poll_new())) {
409                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery poll object.\n");
410                 goto fail;
411         }
412
413         // generate some unique host name (we actually do not care about it)
414         char hostname[17];
415         generate_rand_string(mesh, hostname, sizeof(hostname));
416
417         // Let's set the host name for this server.
418         CattaServerConfig config;
419         catta_server_config_init(&config);
420         config.host_name = catta_strdup(hostname);
421         config.publish_workstation = 0;
422         config.disallow_other_stacks = 0;
423         config.publish_hinfo = 0;
424         config.publish_addresses = 1;
425         config.publish_no_reverse = 1;
426         config.allow_point_to_point = 1;
427
428         /* Allocate a new server */
429         int error;
430         const CattaPoll *poller = catta_simple_poll_get(mesh->catta_poll);
431
432         if(!poller) {
433                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
434                 goto fail;
435         }
436
437         mesh->catta_server = catta_server_new(poller, &config, discovery_server_callback, mesh, &error);
438
439         /* Free the configuration data */
440         catta_server_config_free(&config);
441
442         /* Check whether creating the server object succeeded */
443         if(!mesh->catta_server) {
444                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
445                 goto fail;
446         }
447
448         // Create the service browser
449         if(!(mesh->catta_browser = catta_s_service_browser_new(mesh->catta_server, CATTA_IF_UNSPEC, CATTA_PROTO_UNSPEC, mesh->catta_servicetype, NULL, 0, discovery_browse_callback, mesh))) {
450                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery service browser: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
451                 goto fail;
452         }
453
454         status = true;
455
456 fail:
457
458         pthread_cond_broadcast(&mesh->discovery_cond);
459         pthread_mutex_unlock(&mesh->discovery_mutex);
460
461         if(status) {
462                 catta_simple_poll_loop(mesh->catta_poll);
463         }
464
465         if(mesh->catta_browser) {
466                 catta_s_service_browser_free(mesh->catta_browser);
467                 mesh->catta_browser = NULL;
468         }
469
470         if(mesh->catta_group) {
471                 catta_s_entry_group_reset(mesh->catta_group);
472                 catta_s_entry_group_free(mesh->catta_group);
473                 mesh->catta_group = NULL;
474         }
475
476         if(mesh->catta_server) {
477                 catta_server_free(mesh->catta_server);
478                 mesh->catta_server = NULL;
479         }
480
481         if(mesh->catta_poll) {
482                 catta_simple_poll_free(mesh->catta_poll);
483                 mesh->catta_poll = NULL;
484         }
485
486         if(mesh->catta_servicetype) {
487                 free(mesh->catta_servicetype);
488                 mesh->catta_servicetype = NULL;
489         }
490
491         return NULL;
492 }
493
494 #if defined(__linux)
495 static void netlink_io_handler(event_loop_t *loop, void *data, int flags) {
496         (void)flags;
497         static time_t prev_update;
498         meshlink_handle_t *mesh = data;
499
500         struct {
501                 struct nlmsghdr nlm;
502                 char data[2048];
503         } msg;
504
505         while(true) {
506                 ssize_t result = recv(mesh->pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
507
508                 if(result <= 0) {
509                         if(result == 0 || errno == EAGAIN || errno == EINTR) {
510                                 break;
511                         }
512
513                         logger(mesh, MESHLINK_ERROR, "Reading from Netlink socket failed: %s\n", strerror(errno));
514                         io_set(loop, &mesh->pfroute_io, 0);
515                 }
516
517                 if((size_t)result < sizeof(msg.nlm)) {
518                         logger(mesh, MESHLINK_ERROR, "Invalid Netlink message\n");
519                         break;
520                 }
521
522                 switch(msg.nlm.nlmsg_type) {
523                 case RTM_NEWLINK:
524                 case RTM_DELLINK:
525                 case RTM_NEWADDR:
526                 case RTM_DELADDR:
527                         if(loop->now.tv_sec > prev_update + 5) {
528                                 prev_update = loop->now.tv_sec;
529                                 handle_network_change(mesh, 1);
530                         }
531
532                         break;
533
534                 default:
535                         break;
536                 }
537         }
538 }
539 #elif defined(RTM_NEWADDR)
540 static void pfroute_io_handler(event_loop_t *loop, void *data, int flags) {
541         (void)flags;
542         static time_t prev_update;
543         meshlink_handle_t *mesh = data;
544
545         struct {
546                 struct rt_msghdr rtm;
547                 char data[2048];
548         } msg;
549
550         while(true) {
551                 msg.rtm.rtm_version = 0;
552                 ssize_t result = recv(mesh->pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
553
554                 if(result <= 0) {
555                         if(result == 0 || errno == EAGAIN || errno == EINTR) {
556                                 break;
557                         }
558
559                         logger(mesh, MESHLINK_ERROR, "Reading from PFROUTE socket failed: %s\n", strerror(errno));
560                         io_set(loop, &mesh->pfroute_io, 0);
561                 }
562
563                 if(msg.rtm.rtm_version != RTM_VERSION) {
564                         logger(mesh, MESHLINK_ERROR, "Invalid PFROUTE message version\n");
565                         break;
566                 }
567
568                 switch(msg.rtm.rtm_type) {
569                 case RTM_IFINFO:
570                 case RTM_NEWADDR:
571                 case RTM_DELADDR:
572                         if(loop->now.tv_sec > prev_update + 5) {
573                                 prev_update = loop->now.tv_sec;
574                                 handle_network_change(mesh, 1);
575                         }
576
577                         break;
578
579                 default:
580                         break;
581                 }
582         }
583 }
584 #endif
585
586 bool discovery_start(meshlink_handle_t *mesh) {
587         logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
588
589         assert(mesh);
590         assert(!mesh->catta_poll);
591         assert(!mesh->catta_server);
592         assert(!mesh->catta_browser);
593         assert(!mesh->discovery_threadstarted);
594         assert(!mesh->catta_servicetype);
595
596         if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
597                 abort();
598         }
599
600         // Start the discovery thread
601         if(pthread_create(&mesh->discovery_thread, NULL, discovery_loop, mesh) != 0) {
602                 pthread_mutex_unlock(&mesh->discovery_mutex);
603                 logger(mesh, MESHLINK_ERROR, "Could not start discovery thread: %s\n", strerror(errno));
604                 memset(&mesh->discovery_thread, 0, sizeof(mesh)->discovery_thread);
605                 return false;
606         }
607
608         pthread_cond_wait(&mesh->discovery_cond, &mesh->discovery_mutex);
609         pthread_mutex_unlock(&mesh->discovery_mutex);
610
611         mesh->discovery_threadstarted = true;
612
613 #if defined(__linux)
614         int sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
615
616         if(sock != -1) {
617                 struct sockaddr_nl sa;
618                 memset(&sa, 0, sizeof(sa));
619                 sa.nl_family = AF_NETLINK;
620                 sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR;
621
622                 if(bind(sock, (struct sockaddr *)&sa, sizeof(sa)) != -1) {
623                         io_add(&mesh->loop, &mesh->pfroute_io, netlink_io_handler, mesh, sock, IO_READ);
624                 } else {
625                         logger(mesh, MESHLINK_WARNING, "Could not bind AF_NETLINK socket: %s", strerror(errno));
626                 }
627         } else {
628                 logger(mesh, MESHLINK_WARNING, "Could not open AF_NETLINK socket: %s", strerror(errno));
629         }
630
631 #elif defined(RTM_NEWADDR)
632         int sock = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
633
634         if(sock != -1) {
635                 io_add(&mesh->loop, &mesh->pfroute_io, pfroute_io_handler, mesh, sock, IO_READ);
636         } else {
637                 logger(mesh, MESHLINK_WARNING, "Could not open PF_ROUTE socket: %s", strerror(errno));
638         }
639
640 #endif
641
642         return true;
643 }
644
645 void discovery_stop(meshlink_handle_t *mesh) {
646         logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
647
648         assert(mesh);
649
650         if(mesh->pfroute_io.cb) {
651                 close(mesh->pfroute_io.fd);
652                 io_del(&mesh->loop, &mesh->pfroute_io);
653         }
654
655         // Shut down
656         if(mesh->catta_poll) {
657                 catta_simple_poll_quit(mesh->catta_poll);
658         }
659
660         // Wait for the discovery thread to finish
661         if(mesh->discovery_threadstarted == true) {
662                 if(pthread_join(mesh->discovery_thread, NULL) != 0) {
663                         abort();
664                 }
665
666                 mesh->discovery_threadstarted = false;
667         }
668
669         mesh->catta_interfaces = 0;
670 }