3 #include <catta/core.h>
4 #include <catta/lookup.h>
5 #include <catta/publish.h>
7 #include <catta/simple-watch.h>
8 #include <catta/malloc.h>
9 #include <catta/alternative.h>
10 #include <catta/error.h>
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>
20 #include "meshlink_internal.h"
22 #include "discovery.h"
26 #include "connection.h"
29 #define MESHLINK_MDNS_SERVICE_TYPE "_%s._tcp"
30 #define MESHLINK_MDNS_NAME_KEY "name"
31 #define MESHLINK_MDNS_FINGERPRINT_KEY "fingerprint"
33 static void generate_rand_string(meshlink_handle_t *mesh, char *buffer, size_t size) {
36 for(size_t i = 0; i < (size - 1); ++i) {
37 buffer[i] = 'a' + prng(mesh, 'z' - 'a' + 1);
40 buffer[size - 1] = '\0';
43 static void discovery_entry_group_callback(CattaServer *server, CattaSEntryGroup *group, CattaEntryGroupState state, void *userdata) {
46 meshlink_handle_t *mesh = userdata;
49 assert(mesh->catta_server);
50 assert(mesh->catta_poll);
52 /* Called whenever the entry group state changes */
54 case CATTA_ENTRY_GROUP_ESTABLISHED:
55 /* The entry group has been established successfully */
56 logger(mesh, MESHLINK_DEBUG, "Catta Service successfully established.\n");
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?
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);
70 case CATTA_ENTRY_GROUP_UNCOMMITED:
71 case CATTA_ENTRY_GROUP_REGISTERING:
77 static void discovery_create_services(meshlink_handle_t *mesh) {
78 char *fingerprint = NULL;
79 char *txt_name = NULL;
80 char *txt_fingerprint = NULL;
85 assert(mesh->catta_server);
86 assert(mesh->catta_poll);
87 assert(mesh->catta_servicetype);
90 logger(mesh, MESHLINK_DEBUG, "Adding service\n");
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)));
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);
103 /* Add the service */
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));
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));
120 catta_simple_poll_quit(mesh->catta_poll);
125 free(txt_fingerprint);
128 static void discovery_server_callback(CattaServer *server, CattaServerState state, void *userdata) {
130 meshlink_handle_t *mesh = userdata;
135 case CATTA_SERVER_RUNNING:
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) {
143 if(!mesh->catta_group) {
144 discovery_create_services(mesh);
147 pthread_mutex_unlock(&mesh->mutex);
151 case CATTA_SERVER_COLLISION: {
152 /* A host name collision happened. Let's pick a new name for the server */
154 generate_rand_string(mesh, hostname, sizeof(hostname));
156 if(pthread_mutex_lock(&mesh->mutex) != 0) {
160 assert(mesh->catta_server);
161 assert(mesh->catta_poll);
163 int result = catta_server_set_host_name(mesh->catta_server, hostname);
166 catta_simple_poll_quit(mesh->catta_poll);
169 pthread_mutex_unlock(&mesh->mutex);
173 case CATTA_SERVER_REGISTERING:
174 if(pthread_mutex_lock(&mesh->mutex) != 0) {
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;
186 pthread_mutex_unlock(&mesh->mutex);
190 case CATTA_SERVER_FAILURE:
191 if(pthread_mutex_lock(&mesh->mutex) != 0) {
195 assert(mesh->catta_server);
196 assert(mesh->catta_poll);
198 /* Terminate on failure */
199 catta_simple_poll_quit(mesh->catta_poll);
201 pthread_mutex_unlock(&mesh->mutex);
204 case CATTA_SERVER_INVALID:
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) {
218 meshlink_handle_t *mesh = userdata;
222 if(event != CATTA_RESOLVER_FOUND) {
223 catta_s_service_resolver_free(resolver);
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);
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);
235 if(node_name[0] == '=' && node_fp[0] == '=') {
236 if(pthread_mutex_lock(&mesh->mutex) != 0) {
242 meshlink_node_t *node = meshlink_get_node(mesh, node_name);
245 logger(mesh, MESHLINK_INFO, "Node %s is part of the mesh network.\n", node->name);
248 memset(&naddress, 0, sizeof(naddress));
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;
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));
266 naddress.unknown.family = AF_UNKNOWN;
270 if(naddress.unknown.family != AF_UNKNOWN) {
271 node_t *n = (node_t *)node;
272 connection_t *c = n->connection;
274 n->catta_address = naddress;
275 node_add_recent_address(mesh, n, &naddress);
277 if(c && c->outgoing && !c->status.active) {
278 c->outgoing->timeout = 0;
280 if(c->outgoing->ev.cb) {
281 timeout_set(&mesh->loop, &c->outgoing->ev, &(struct timespec) {
286 c->last_ping_time = -3600;
290 logger(mesh, MESHLINK_WARNING, "Could not resolve node %s to a known address family type.\n", node->name);
293 logger(mesh, MESHLINK_WARNING, "Node %s is not part of the mesh network.\n", node_name);
296 pthread_mutex_unlock(&mesh->mutex);
300 catta_s_service_resolver_free(resolver);
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) {
306 meshlink_handle_t *mesh = userdata;
308 /* Called whenever a new services becomes available on the LAN or is removed from the LAN */
310 case CATTA_BROWSER_FAILURE:
311 if(pthread_mutex_lock(&mesh->mutex) != 0) {
315 catta_simple_poll_quit(mesh->catta_poll);
316 pthread_mutex_unlock(&mesh->mutex);
319 case CATTA_BROWSER_NEW:
320 if(pthread_mutex_lock(&mesh->mutex) != 0) {
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);
329 case CATTA_BROWSER_REMOVE:
330 if(pthread_mutex_lock(&mesh->mutex) != 0) {
334 handle_network_change(mesh, --mesh->catta_interfaces);
335 pthread_mutex_unlock(&mesh->mutex);
338 case CATTA_BROWSER_ALL_FOR_NOW:
339 case CATTA_BROWSER_CACHE_EXHAUSTED:
344 static void discovery_log_cb(CattaLogLevel level, const char *txt) {
345 meshlink_log_level_t mlevel = MESHLINK_CRITICAL;
348 case CATTA_LOG_ERROR:
349 mlevel = MESHLINK_ERROR;
353 mlevel = MESHLINK_WARNING;
356 case CATTA_LOG_NOTICE:
358 mlevel = MESHLINK_INFO;
361 case CATTA_LOG_DEBUG:
363 mlevel = MESHLINK_DEBUG;
367 logger(NULL, mlevel, "%s\n", txt);
370 static void *discovery_loop(void *userdata) {
372 meshlink_handle_t *mesh = userdata;
375 if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
380 catta_set_log_function(discovery_log_cb);
382 // create service type string
383 char appname[strlen(mesh->appname) + 2];
384 strcpy(appname, mesh->appname);
386 for(char *p = appname; *p; p++) {
387 if(!isalnum(*p) && *p != '_' && *p != '-') {
397 size_t servicetype_strlen = sizeof(MESHLINK_MDNS_SERVICE_TYPE) + strlen(appname) + 1;
398 mesh->catta_servicetype = malloc(servicetype_strlen);
400 if(mesh->catta_servicetype == NULL) {
401 logger(mesh, MESHLINK_ERROR, "Failed to allocate memory for service type string.\n");
405 snprintf(mesh->catta_servicetype, servicetype_strlen, MESHLINK_MDNS_SERVICE_TYPE, appname);
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");
413 // generate some unique host name (we actually do not care about it)
415 generate_rand_string(mesh, hostname, sizeof(hostname));
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;
428 /* Allocate a new server */
430 const CattaPoll *poller = catta_simple_poll_get(mesh->catta_poll);
433 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
437 mesh->catta_server = catta_server_new(poller, &config, discovery_server_callback, mesh, &error);
439 /* Free the configuration data */
440 catta_server_config_free(&config);
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));
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)));
458 pthread_cond_broadcast(&mesh->discovery_cond);
459 pthread_mutex_unlock(&mesh->discovery_mutex);
462 catta_simple_poll_loop(mesh->catta_poll);
465 if(mesh->catta_browser) {
466 catta_s_service_browser_free(mesh->catta_browser);
467 mesh->catta_browser = NULL;
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;
476 if(mesh->catta_server) {
477 catta_server_free(mesh->catta_server);
478 mesh->catta_server = NULL;
481 if(mesh->catta_poll) {
482 catta_simple_poll_free(mesh->catta_poll);
483 mesh->catta_poll = NULL;
486 if(mesh->catta_servicetype) {
487 free(mesh->catta_servicetype);
488 mesh->catta_servicetype = NULL;
495 static void netlink_io_handler(event_loop_t *loop, void *data, int flags) {
497 static time_t prev_update;
498 meshlink_handle_t *mesh = data;
506 ssize_t result = recv(mesh->pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
509 if(result == 0 || errno == EAGAIN || errno == EINTR) {
513 logger(mesh, MESHLINK_ERROR, "Reading from Netlink socket failed: %s\n", strerror(errno));
514 io_set(loop, &mesh->pfroute_io, 0);
517 if((size_t)result < sizeof(msg.nlm)) {
518 logger(mesh, MESHLINK_ERROR, "Invalid Netlink message\n");
522 switch(msg.nlm.nlmsg_type) {
527 if(loop->now.tv_sec > prev_update + 5) {
528 prev_update = loop->now.tv_sec;
529 handle_network_change(mesh, 1);
539 #elif defined(RTM_NEWADDR)
540 static void pfroute_io_handler(event_loop_t *loop, void *data, int flags) {
542 static time_t prev_update;
543 meshlink_handle_t *mesh = data;
546 struct rt_msghdr rtm;
551 msg.rtm.rtm_version = 0;
552 ssize_t result = recv(mesh->pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
555 if(result == 0 || errno == EAGAIN || errno == EINTR) {
559 logger(mesh, MESHLINK_ERROR, "Reading from PFROUTE socket failed: %s\n", strerror(errno));
560 io_set(loop, &mesh->pfroute_io, 0);
563 if(msg.rtm.rtm_version != RTM_VERSION) {
564 logger(mesh, MESHLINK_ERROR, "Invalid PFROUTE message version\n");
568 switch(msg.rtm.rtm_type) {
572 if(loop->now.tv_sec > prev_update + 5) {
573 prev_update = loop->now.tv_sec;
574 handle_network_change(mesh, 1);
586 bool discovery_start(meshlink_handle_t *mesh) {
587 logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
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);
596 if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
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);
608 pthread_cond_wait(&mesh->discovery_cond, &mesh->discovery_mutex);
609 pthread_mutex_unlock(&mesh->discovery_mutex);
611 mesh->discovery_threadstarted = true;
614 int sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
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;
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);
625 logger(mesh, MESHLINK_WARNING, "Could not bind AF_NETLINK socket: %s", strerror(errno));
628 logger(mesh, MESHLINK_WARNING, "Could not open AF_NETLINK socket: %s", strerror(errno));
631 #elif defined(RTM_NEWADDR)
632 int sock = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
635 io_add(&mesh->loop, &mesh->pfroute_io, pfroute_io_handler, mesh, sock, IO_READ);
637 logger(mesh, MESHLINK_WARNING, "Could not open PF_ROUTE socket: %s", strerror(errno));
645 void discovery_stop(meshlink_handle_t *mesh) {
646 logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
650 if(mesh->pfroute_io.cb) {
651 close(mesh->pfroute_io.fd);
652 io_del(&mesh->loop, &mesh->pfroute_io);
656 if(mesh->catta_poll) {
657 catta_simple_poll_quit(mesh->catta_poll);
660 // Wait for the discovery thread to finish
661 if(mesh->discovery_threadstarted == true) {
662 if(pthread_join(mesh->discovery_thread, NULL) != 0) {
666 mesh->discovery_threadstarted = false;
669 mesh->catta_interfaces = 0;