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 #include "meshlink_internal.h"
13 #include "discovery.h"
17 #include "connection.h"
20 #define MESHLINK_MDNS_SERVICE_TYPE "_%s._tcp"
21 #define MESHLINK_MDNS_NAME_KEY "name"
22 #define MESHLINK_MDNS_FINGERPRINT_KEY "fingerprint"
24 static void generate_rand_string(meshlink_handle_t *mesh, char *buffer, size_t size) {
27 for(size_t i = 0; i < (size - 1); ++i) {
28 buffer[i] = 'a' + prng(mesh, 'z' - 'a' + 1);
31 buffer[size - 1] = '\0';
34 static void discovery_entry_group_callback(CattaServer *server, CattaSEntryGroup *group, CattaEntryGroupState state, void *userdata) {
37 meshlink_handle_t *mesh = userdata;
40 assert(mesh->catta_server);
41 assert(mesh->catta_poll);
43 /* Called whenever the entry group state changes */
45 case CATTA_ENTRY_GROUP_ESTABLISHED:
46 /* The entry group has been established successfully */
47 logger(mesh, MESHLINK_DEBUG, "Catta Service successfully established.\n");
50 case CATTA_ENTRY_GROUP_COLLISION:
51 logger(mesh, MESHLINK_WARNING, "Catta Service collision.\n");
52 // @TODO can we just set a new name and retry?
55 case CATTA_ENTRY_GROUP_FAILURE :
56 /* Some kind of failure happened while we were registering our services */
57 logger(mesh, MESHLINK_ERROR, "Catta Entry group failure: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
58 catta_simple_poll_quit(mesh->catta_poll);
61 case CATTA_ENTRY_GROUP_UNCOMMITED:
62 case CATTA_ENTRY_GROUP_REGISTERING:
68 static void discovery_create_services(meshlink_handle_t *mesh) {
69 char *fingerprint = NULL;
70 char *txt_name = NULL;
71 char *txt_fingerprint = NULL;
76 assert(mesh->catta_server);
77 assert(mesh->catta_poll);
78 assert(mesh->catta_servicetype);
81 logger(mesh, MESHLINK_DEBUG, "Adding service\n");
83 /* Ifthis is the first time we're called, let's create a new entry group */
84 if(!(mesh->catta_group = catta_s_entry_group_new(mesh->catta_server, discovery_entry_group_callback, mesh))) {
85 logger(mesh, MESHLINK_ERROR, "catta_entry_group_new() failed: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
89 /* Create txt records */
90 fingerprint = meshlink_get_fingerprint(mesh, (meshlink_node_t *)mesh->self);
91 xasprintf(&txt_name, "%s=%s", MESHLINK_MDNS_NAME_KEY, mesh->name);
92 xasprintf(&txt_fingerprint, "%s=%s", MESHLINK_MDNS_FINGERPRINT_KEY, fingerprint);
97 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) {
98 logger(mesh, MESHLINK_ERROR, "Failed to add service: %s\n", catta_strerror(ret));
102 /* Tell the server to register the service */
103 if((ret = catta_s_entry_group_commit(mesh->catta_group)) < 0) {
104 logger(mesh, MESHLINK_ERROR, "Failed to commit entry_group: %s\n", catta_strerror(ret));
111 catta_simple_poll_quit(mesh->catta_poll);
116 free(txt_fingerprint);
119 static void discovery_server_callback(CattaServer *server, CattaServerState state, void *userdata) {
121 meshlink_handle_t *mesh = userdata;
126 case CATTA_SERVER_RUNNING:
128 /* The serve has startup successfully and registered its host
129 * name on the network, so it's time to create our services */
130 if(pthread_mutex_lock(&mesh->mutex) != 0) {
134 if(!mesh->catta_group) {
135 discovery_create_services(mesh);
138 pthread_mutex_unlock(&mesh->mutex);
142 case CATTA_SERVER_COLLISION: {
143 /* A host name collision happened. Let's pick a new name for the server */
145 generate_rand_string(mesh, hostname, sizeof(hostname));
147 if(pthread_mutex_lock(&mesh->mutex) != 0) {
151 assert(mesh->catta_server);
152 assert(mesh->catta_poll);
154 int result = catta_server_set_host_name(mesh->catta_server, hostname);
157 catta_simple_poll_quit(mesh->catta_poll);
160 pthread_mutex_unlock(&mesh->mutex);
164 case CATTA_SERVER_REGISTERING:
165 if(pthread_mutex_lock(&mesh->mutex) != 0) {
169 /* Let's drop our registered services. When the server is back
170 * in CATTA_SERVER_RUNNING state we will register them
171 * again with the new host name. */
172 if(mesh->catta_group) {
173 catta_s_entry_group_reset(mesh->catta_group);
174 mesh->catta_group = NULL;
177 pthread_mutex_unlock(&mesh->mutex);
181 case CATTA_SERVER_FAILURE:
182 if(pthread_mutex_lock(&mesh->mutex) != 0) {
186 assert(mesh->catta_server);
187 assert(mesh->catta_poll);
189 /* Terminate on failure */
190 catta_simple_poll_quit(mesh->catta_poll);
192 pthread_mutex_unlock(&mesh->mutex);
195 case CATTA_SERVER_INVALID:
200 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) {
209 meshlink_handle_t *mesh = userdata;
213 if(event != CATTA_RESOLVER_FOUND) {
214 catta_s_service_resolver_free(resolver);
218 // retrieve fingerprint
219 CattaStringList *node_name_li = catta_string_list_find(txt, MESHLINK_MDNS_NAME_KEY);
220 CattaStringList *node_fp_li = catta_string_list_find(txt, MESHLINK_MDNS_FINGERPRINT_KEY);
222 if(node_name_li && node_fp_li) {
223 char *node_name = (char *)catta_string_list_get_text(node_name_li) + strlen(MESHLINK_MDNS_NAME_KEY);
224 char *node_fp = (char *)catta_string_list_get_text(node_fp_li) + strlen(MESHLINK_MDNS_FINGERPRINT_KEY);
226 if(node_name[0] == '=' && node_fp[0] == '=') {
227 if(pthread_mutex_lock(&mesh->mutex) != 0) {
233 meshlink_node_t *node = meshlink_get_node(mesh, node_name);
236 logger(mesh, MESHLINK_INFO, "Node %s is part of the mesh network.\n", node->name);
239 memset(&naddress, 0, sizeof(naddress));
241 switch(address->proto) {
242 case CATTA_PROTO_INET: {
243 naddress.in.sin_family = AF_INET;
244 naddress.in.sin_port = htons(port);
245 naddress.in.sin_addr.s_addr = address->data.ipv4.address;
249 case CATTA_PROTO_INET6: {
250 naddress.in6.sin6_family = AF_INET6;
251 naddress.in6.sin6_port = htons(port);
252 memcpy(naddress.in6.sin6_addr.s6_addr, address->data.ipv6.address, sizeof(naddress.in6.sin6_addr.s6_addr));
257 naddress.unknown.family = AF_UNKNOWN;
261 if(naddress.unknown.family != AF_UNKNOWN) {
262 node_t *n = (node_t *)node;
263 connection_t *c = n->connection;
265 n->catta_address = naddress;
266 node_add_recent_address(mesh, n, &naddress);
268 if(c && c->outgoing && !c->status.active) {
269 c->outgoing->timeout = 0;
271 if(c->outgoing->ev.cb) {
272 timeout_set(&mesh->loop, &c->outgoing->ev, &(struct timespec) {
277 c->last_ping_time = -3600;
281 logger(mesh, MESHLINK_WARNING, "Could not resolve node %s to a known address family type.\n", node->name);
284 logger(mesh, MESHLINK_WARNING, "Node %s is not part of the mesh network.\n", node_name);
287 pthread_mutex_unlock(&mesh->mutex);
291 catta_s_service_resolver_free(resolver);
294 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) {
297 meshlink_handle_t *mesh = userdata;
299 /* Called whenever a new services becomes available on the LAN or is removed from the LAN */
301 case CATTA_BROWSER_FAILURE:
302 if(pthread_mutex_lock(&mesh->mutex) != 0) {
306 catta_simple_poll_quit(mesh->catta_poll);
307 pthread_mutex_unlock(&mesh->mutex);
310 case CATTA_BROWSER_NEW:
311 if(pthread_mutex_lock(&mesh->mutex) != 0) {
315 catta_s_service_resolver_new(mesh->catta_server, interface_, protocol, name, type, domain, CATTA_PROTO_UNSPEC, 0, discovery_resolve_callback, mesh);
316 handle_network_change(mesh, ++mesh->catta_interfaces);
317 pthread_mutex_unlock(&mesh->mutex);
320 case CATTA_BROWSER_REMOVE:
321 if(pthread_mutex_lock(&mesh->mutex) != 0) {
325 handle_network_change(mesh, --mesh->catta_interfaces);
326 pthread_mutex_unlock(&mesh->mutex);
329 case CATTA_BROWSER_ALL_FOR_NOW:
330 case CATTA_BROWSER_CACHE_EXHAUSTED:
335 static void discovery_log_cb(CattaLogLevel level, const char *txt) {
336 meshlink_log_level_t mlevel = MESHLINK_CRITICAL;
339 case CATTA_LOG_ERROR:
340 mlevel = MESHLINK_ERROR;
344 mlevel = MESHLINK_WARNING;
347 case CATTA_LOG_NOTICE:
349 mlevel = MESHLINK_INFO;
352 case CATTA_LOG_DEBUG:
354 mlevel = MESHLINK_DEBUG;
358 logger(NULL, mlevel, "%s\n", txt);
361 static void *discovery_loop(void *userdata) {
363 meshlink_handle_t *mesh = userdata;
366 if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
371 catta_set_log_function(discovery_log_cb);
373 // create service type string
374 char appname[strlen(mesh->appname) + 2];
375 strcpy(appname, mesh->appname);
377 for(char *p = appname; *p; p++) {
378 if(!isalnum(*p) && *p != '_' && *p != '-') {
388 size_t servicetype_strlen = sizeof(MESHLINK_MDNS_SERVICE_TYPE) + strlen(appname) + 1;
389 mesh->catta_servicetype = malloc(servicetype_strlen);
391 if(mesh->catta_servicetype == NULL) {
392 logger(mesh, MESHLINK_ERROR, "Failed to allocate memory for service type string.\n");
396 snprintf(mesh->catta_servicetype, servicetype_strlen, MESHLINK_MDNS_SERVICE_TYPE, appname);
398 // Allocate discovery loop object
399 if(!(mesh->catta_poll = catta_simple_poll_new())) {
400 logger(mesh, MESHLINK_ERROR, "Failed to create discovery poll object.\n");
404 // generate some unique host name (we actually do not care about it)
406 generate_rand_string(mesh, hostname, sizeof(hostname));
408 // Let's set the host name for this server.
409 CattaServerConfig config;
410 catta_server_config_init(&config);
411 config.host_name = catta_strdup(hostname);
412 config.publish_workstation = 0;
413 config.disallow_other_stacks = 0;
414 config.publish_hinfo = 0;
415 config.publish_addresses = 1;
416 config.publish_no_reverse = 1;
417 config.allow_point_to_point = 1;
419 /* Allocate a new server */
421 mesh->catta_server = catta_server_new(catta_simple_poll_get(mesh->catta_poll), &config, discovery_server_callback, mesh, &error);
423 /* Free the configuration data */
424 catta_server_config_free(&config);
426 /* Check whether creating the server object succeeded */
427 if(!mesh->catta_server) {
428 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
432 // Create the service browser
433 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))) {
434 logger(mesh, MESHLINK_ERROR, "Failed to create discovery service browser: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
442 pthread_cond_broadcast(&mesh->discovery_cond);
443 pthread_mutex_unlock(&mesh->discovery_mutex);
446 catta_simple_poll_loop(mesh->catta_poll);
449 if(mesh->catta_browser) {
450 catta_s_service_browser_free(mesh->catta_browser);
451 mesh->catta_browser = NULL;
454 if(mesh->catta_group) {
455 catta_s_entry_group_reset(mesh->catta_group);
456 catta_s_entry_group_free(mesh->catta_group);
457 mesh->catta_group = NULL;
460 if(mesh->catta_server) {
461 catta_server_free(mesh->catta_server);
462 mesh->catta_server = NULL;
465 if(mesh->catta_poll) {
466 catta_simple_poll_free(mesh->catta_poll);
467 mesh->catta_poll = NULL;
470 if(mesh->catta_servicetype) {
471 free(mesh->catta_servicetype);
472 mesh->catta_servicetype = NULL;
478 bool discovery_start(meshlink_handle_t *mesh) {
479 logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
482 assert(!mesh->catta_poll);
483 assert(!mesh->catta_server);
484 assert(!mesh->catta_browser);
485 assert(!mesh->discovery_threadstarted);
486 assert(!mesh->catta_servicetype);
488 if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
492 // Start the discovery thread
493 if(pthread_create(&mesh->discovery_thread, NULL, discovery_loop, mesh) != 0) {
494 pthread_mutex_unlock(&mesh->discovery_mutex);
495 logger(mesh, MESHLINK_ERROR, "Could not start discovery thread: %s\n", strerror(errno));
496 memset(&mesh->discovery_thread, 0, sizeof(mesh)->discovery_thread);
500 pthread_cond_wait(&mesh->discovery_cond, &mesh->discovery_mutex);
501 pthread_mutex_unlock(&mesh->discovery_mutex);
503 mesh->discovery_threadstarted = true;
508 void discovery_stop(meshlink_handle_t *mesh) {
509 logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
514 if(mesh->catta_poll) {
515 catta_simple_poll_quit(mesh->catta_poll);
518 // Wait for the discovery thread to finish
519 if(mesh->discovery_threadstarted == true) {
520 if(pthread_join(mesh->discovery_thread, NULL) != 0) {
524 mesh->discovery_threadstarted = false;
527 mesh->catta_interfaces = 0;