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>
16 #include "meshlink_internal.h"
18 #include "discovery.h"
22 #include "connection.h"
25 #define MESHLINK_MDNS_SERVICE_TYPE "_%s._tcp"
26 #define MESHLINK_MDNS_NAME_KEY "name"
27 #define MESHLINK_MDNS_FINGERPRINT_KEY "fingerprint"
29 static void generate_rand_string(meshlink_handle_t *mesh, char *buffer, size_t size) {
32 for(size_t i = 0; i < (size - 1); ++i) {
33 buffer[i] = 'a' + prng(mesh, 'z' - 'a' + 1);
36 buffer[size - 1] = '\0';
39 static void discovery_entry_group_callback(CattaServer *server, CattaSEntryGroup *group, CattaEntryGroupState state, void *userdata) {
42 meshlink_handle_t *mesh = userdata;
45 assert(mesh->catta_server);
46 assert(mesh->catta_poll);
48 /* Called whenever the entry group state changes */
50 case CATTA_ENTRY_GROUP_ESTABLISHED:
51 /* The entry group has been established successfully */
52 logger(mesh, MESHLINK_DEBUG, "Catta Service successfully established.\n");
55 case CATTA_ENTRY_GROUP_COLLISION:
56 logger(mesh, MESHLINK_WARNING, "Catta Service collision.\n");
57 // @TODO can we just set a new name and retry?
60 case CATTA_ENTRY_GROUP_FAILURE :
61 /* Some kind of failure happened while we were registering our services */
62 logger(mesh, MESHLINK_ERROR, "Catta Entry group failure: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
63 catta_simple_poll_quit(mesh->catta_poll);
66 case CATTA_ENTRY_GROUP_UNCOMMITED:
67 case CATTA_ENTRY_GROUP_REGISTERING:
73 static void discovery_create_services(meshlink_handle_t *mesh) {
74 char *fingerprint = NULL;
75 char *txt_name = NULL;
76 char *txt_fingerprint = NULL;
81 assert(mesh->catta_server);
82 assert(mesh->catta_poll);
83 assert(mesh->catta_servicetype);
86 logger(mesh, MESHLINK_DEBUG, "Adding service\n");
88 /* Ifthis is the first time we're called, let's create a new entry group */
89 if(!(mesh->catta_group = catta_s_entry_group_new(mesh->catta_server, discovery_entry_group_callback, mesh))) {
90 logger(mesh, MESHLINK_ERROR, "catta_entry_group_new() failed: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
94 /* Create txt records */
95 fingerprint = meshlink_get_fingerprint(mesh, (meshlink_node_t *)mesh->self);
96 xasprintf(&txt_name, "%s=%s", MESHLINK_MDNS_NAME_KEY, mesh->name);
97 xasprintf(&txt_fingerprint, "%s=%s", MESHLINK_MDNS_FINGERPRINT_KEY, fingerprint);
102 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) {
103 logger(mesh, MESHLINK_ERROR, "Failed to add service: %s\n", catta_strerror(ret));
107 /* Tell the server to register the service */
108 if((ret = catta_s_entry_group_commit(mesh->catta_group)) < 0) {
109 logger(mesh, MESHLINK_ERROR, "Failed to commit entry_group: %s\n", catta_strerror(ret));
116 catta_simple_poll_quit(mesh->catta_poll);
121 free(txt_fingerprint);
124 static void discovery_server_callback(CattaServer *server, CattaServerState state, void *userdata) {
126 meshlink_handle_t *mesh = userdata;
131 case CATTA_SERVER_RUNNING:
133 /* The serve has startup successfully and registered its host
134 * name on the network, so it's time to create our services */
135 if(pthread_mutex_lock(&mesh->mutex) != 0) {
139 if(!mesh->catta_group) {
140 discovery_create_services(mesh);
143 pthread_mutex_unlock(&mesh->mutex);
147 case CATTA_SERVER_COLLISION: {
148 /* A host name collision happened. Let's pick a new name for the server */
150 generate_rand_string(mesh, hostname, sizeof(hostname));
152 if(pthread_mutex_lock(&mesh->mutex) != 0) {
156 assert(mesh->catta_server);
157 assert(mesh->catta_poll);
159 int result = catta_server_set_host_name(mesh->catta_server, hostname);
162 catta_simple_poll_quit(mesh->catta_poll);
165 pthread_mutex_unlock(&mesh->mutex);
169 case CATTA_SERVER_REGISTERING:
170 if(pthread_mutex_lock(&mesh->mutex) != 0) {
174 /* Let's drop our registered services. When the server is back
175 * in CATTA_SERVER_RUNNING state we will register them
176 * again with the new host name. */
177 if(mesh->catta_group) {
178 catta_s_entry_group_reset(mesh->catta_group);
179 mesh->catta_group = NULL;
182 pthread_mutex_unlock(&mesh->mutex);
186 case CATTA_SERVER_FAILURE:
187 if(pthread_mutex_lock(&mesh->mutex) != 0) {
191 assert(mesh->catta_server);
192 assert(mesh->catta_poll);
194 /* Terminate on failure */
195 catta_simple_poll_quit(mesh->catta_poll);
197 pthread_mutex_unlock(&mesh->mutex);
200 case CATTA_SERVER_INVALID:
205 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) {
214 meshlink_handle_t *mesh = userdata;
218 if(event != CATTA_RESOLVER_FOUND) {
219 catta_s_service_resolver_free(resolver);
223 // retrieve fingerprint
224 CattaStringList *node_name_li = catta_string_list_find(txt, MESHLINK_MDNS_NAME_KEY);
225 CattaStringList *node_fp_li = catta_string_list_find(txt, MESHLINK_MDNS_FINGERPRINT_KEY);
227 if(node_name_li && node_fp_li) {
228 char *node_name = (char *)catta_string_list_get_text(node_name_li) + strlen(MESHLINK_MDNS_NAME_KEY);
229 char *node_fp = (char *)catta_string_list_get_text(node_fp_li) + strlen(MESHLINK_MDNS_FINGERPRINT_KEY);
231 if(node_name[0] == '=' && node_fp[0] == '=') {
232 if(pthread_mutex_lock(&mesh->mutex) != 0) {
238 meshlink_node_t *node = meshlink_get_node(mesh, node_name);
241 logger(mesh, MESHLINK_INFO, "Node %s is part of the mesh network.\n", node->name);
244 memset(&naddress, 0, sizeof(naddress));
246 switch(address->proto) {
247 case CATTA_PROTO_INET: {
248 naddress.in.sin_family = AF_INET;
249 naddress.in.sin_port = htons(port);
250 naddress.in.sin_addr.s_addr = address->data.ipv4.address;
254 case CATTA_PROTO_INET6: {
255 naddress.in6.sin6_family = AF_INET6;
256 naddress.in6.sin6_port = htons(port);
257 memcpy(naddress.in6.sin6_addr.s6_addr, address->data.ipv6.address, sizeof(naddress.in6.sin6_addr.s6_addr));
262 naddress.unknown.family = AF_UNKNOWN;
266 if(naddress.unknown.family != AF_UNKNOWN) {
267 node_t *n = (node_t *)node;
268 connection_t *c = n->connection;
270 n->catta_address = naddress;
271 node_add_recent_address(mesh, n, &naddress);
273 if(c && c->outgoing && !c->status.active) {
274 c->outgoing->timeout = 0;
276 if(c->outgoing->ev.cb) {
277 timeout_set(&mesh->loop, &c->outgoing->ev, &(struct timespec) {
282 c->last_ping_time = -3600;
286 logger(mesh, MESHLINK_WARNING, "Could not resolve node %s to a known address family type.\n", node->name);
289 logger(mesh, MESHLINK_WARNING, "Node %s is not part of the mesh network.\n", node_name);
292 pthread_mutex_unlock(&mesh->mutex);
296 catta_s_service_resolver_free(resolver);
299 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) {
302 meshlink_handle_t *mesh = userdata;
304 /* Called whenever a new services becomes available on the LAN or is removed from the LAN */
306 case CATTA_BROWSER_FAILURE:
307 if(pthread_mutex_lock(&mesh->mutex) != 0) {
311 catta_simple_poll_quit(mesh->catta_poll);
312 pthread_mutex_unlock(&mesh->mutex);
315 case CATTA_BROWSER_NEW:
316 if(pthread_mutex_lock(&mesh->mutex) != 0) {
320 catta_s_service_resolver_new(mesh->catta_server, interface_, protocol, name, type, domain, CATTA_PROTO_UNSPEC, 0, discovery_resolve_callback, mesh);
321 handle_network_change(mesh, ++mesh->catta_interfaces);
322 pthread_mutex_unlock(&mesh->mutex);
325 case CATTA_BROWSER_REMOVE:
326 if(pthread_mutex_lock(&mesh->mutex) != 0) {
330 handle_network_change(mesh, --mesh->catta_interfaces);
331 pthread_mutex_unlock(&mesh->mutex);
334 case CATTA_BROWSER_ALL_FOR_NOW:
335 case CATTA_BROWSER_CACHE_EXHAUSTED:
340 static void discovery_log_cb(CattaLogLevel level, const char *txt) {
341 meshlink_log_level_t mlevel = MESHLINK_CRITICAL;
344 case CATTA_LOG_ERROR:
345 mlevel = MESHLINK_ERROR;
349 mlevel = MESHLINK_WARNING;
352 case CATTA_LOG_NOTICE:
354 mlevel = MESHLINK_INFO;
357 case CATTA_LOG_DEBUG:
359 mlevel = MESHLINK_DEBUG;
363 logger(NULL, mlevel, "%s\n", txt);
366 static void *discovery_loop(void *userdata) {
368 meshlink_handle_t *mesh = userdata;
371 if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
376 catta_set_log_function(discovery_log_cb);
378 // create service type string
379 char appname[strlen(mesh->appname) + 2];
380 strcpy(appname, mesh->appname);
382 for(char *p = appname; *p; p++) {
383 if(!isalnum(*p) && *p != '_' && *p != '-') {
393 size_t servicetype_strlen = sizeof(MESHLINK_MDNS_SERVICE_TYPE) + strlen(appname) + 1;
394 mesh->catta_servicetype = malloc(servicetype_strlen);
396 if(mesh->catta_servicetype == NULL) {
397 logger(mesh, MESHLINK_ERROR, "Failed to allocate memory for service type string.\n");
401 snprintf(mesh->catta_servicetype, servicetype_strlen, MESHLINK_MDNS_SERVICE_TYPE, appname);
403 // Allocate discovery loop object
404 if(!(mesh->catta_poll = catta_simple_poll_new())) {
405 logger(mesh, MESHLINK_ERROR, "Failed to create discovery poll object.\n");
409 // generate some unique host name (we actually do not care about it)
411 generate_rand_string(mesh, hostname, sizeof(hostname));
413 // Let's set the host name for this server.
414 CattaServerConfig config;
415 catta_server_config_init(&config);
416 config.host_name = catta_strdup(hostname);
417 config.publish_workstation = 0;
418 config.disallow_other_stacks = 0;
419 config.publish_hinfo = 0;
420 config.publish_addresses = 1;
421 config.publish_no_reverse = 1;
422 config.allow_point_to_point = 1;
424 /* Allocate a new server */
426 const CattaPoll *poller = catta_simple_poll_get(mesh->catta_poll);
429 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
433 mesh->catta_server = catta_server_new(poller, &config, discovery_server_callback, mesh, &error);
435 /* Free the configuration data */
436 catta_server_config_free(&config);
438 /* Check whether creating the server object succeeded */
439 if(!mesh->catta_server) {
440 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
444 // Create the service browser
445 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))) {
446 logger(mesh, MESHLINK_ERROR, "Failed to create discovery service browser: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
454 pthread_cond_broadcast(&mesh->discovery_cond);
455 pthread_mutex_unlock(&mesh->discovery_mutex);
458 catta_simple_poll_loop(mesh->catta_poll);
461 if(mesh->catta_browser) {
462 catta_s_service_browser_free(mesh->catta_browser);
463 mesh->catta_browser = NULL;
466 if(mesh->catta_group) {
467 catta_s_entry_group_reset(mesh->catta_group);
468 catta_s_entry_group_free(mesh->catta_group);
469 mesh->catta_group = NULL;
472 if(mesh->catta_server) {
473 catta_server_free(mesh->catta_server);
474 mesh->catta_server = NULL;
477 if(mesh->catta_poll) {
478 catta_simple_poll_free(mesh->catta_poll);
479 mesh->catta_poll = NULL;
482 if(mesh->catta_servicetype) {
483 free(mesh->catta_servicetype);
484 mesh->catta_servicetype = NULL;
491 static void pfroute_io_handler(event_loop_t *loop, void *data, int flags) {
493 static time_t prev_update;
494 meshlink_handle_t *mesh = data;
497 struct rt_msghdr rtm;
502 msg.rtm.rtm_version = 0;
503 ssize_t result = recv(mesh->pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
506 if(result == 0 || errno == EAGAIN || errno == EINTR) {
510 logger(mesh, MESHLINK_ERROR, "Reading from PFROUTE socket failed: %s\n", strerror(errno));
511 io_set(loop, &mesh->pfroute_io, 0);
514 if(msg.rtm.rtm_version != RTM_VERSION) {
515 logger(mesh, MESHLINK_ERROR, "Invalid PFROUTE message version\n");
519 switch(msg.rtm.rtm_type) {
523 if(loop->now.tv_sec > prev_update + 5) {
524 prev_update = loop->now.tv_sec;
525 handle_network_change(mesh, 1);
537 bool discovery_start(meshlink_handle_t *mesh) {
538 logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
541 assert(!mesh->catta_poll);
542 assert(!mesh->catta_server);
543 assert(!mesh->catta_browser);
544 assert(!mesh->discovery_threadstarted);
545 assert(!mesh->catta_servicetype);
547 if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
551 // Start the discovery thread
552 if(pthread_create(&mesh->discovery_thread, NULL, discovery_loop, mesh) != 0) {
553 pthread_mutex_unlock(&mesh->discovery_mutex);
554 logger(mesh, MESHLINK_ERROR, "Could not start discovery thread: %s\n", strerror(errno));
555 memset(&mesh->discovery_thread, 0, sizeof(mesh)->discovery_thread);
559 pthread_cond_wait(&mesh->discovery_cond, &mesh->discovery_mutex);
560 pthread_mutex_unlock(&mesh->discovery_mutex);
562 mesh->discovery_threadstarted = true;
565 int sock = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
568 io_add(&mesh->loop, &mesh->pfroute_io, pfroute_io_handler, mesh, sock, IO_READ);
570 logger(mesh, MESHLINK_WARNING, "Could not open PF_ROUTE socket: %s", strerror(errno));
578 void discovery_stop(meshlink_handle_t *mesh) {
579 logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
585 if(mesh->pfroute_io.cb) {
586 close(mesh->pfroute_io.fd);
587 io_del(&mesh->loop, &mesh->pfroute_io);
593 if(mesh->catta_poll) {
594 catta_simple_poll_quit(mesh->catta_poll);
597 // Wait for the discovery thread to finish
598 if(mesh->discovery_threadstarted == true) {
599 if(pthread_join(mesh->discovery_thread, NULL) != 0) {
603 mesh->discovery_threadstarted = false;
606 mesh->catta_interfaces = 0;