1 #include <catta/core.h>
2 #include <catta/lookup.h>
3 #include <catta/publish.h>
5 #include <catta/simple-watch.h>
6 #include <catta/malloc.h>
7 #include <catta/alternative.h>
8 #include <catta/error.h>
10 #include "meshlink_internal.h"
11 #include "discovery.h"
15 #include "connection.h"
19 #include <netinet/in.h>
21 #define MESHLINK_MDNS_SERVICE_TYPE "_%s._tcp"
22 #define MESHLINK_MDNS_NAME_KEY "name"
23 #define MESHLINK_MDNS_FINGERPRINT_KEY "fingerprint"
25 static void generate_rand_string(char *buffer, size_t size) {
26 for(size_t i = 0; i < (size - 1); ++i) {
27 buffer[i] = 'a' + (rand() % ('z' - 'a' + 1));
30 buffer[size - 1] = '\0';
33 static void discovery_entry_group_callback(CattaServer *server, CattaSEntryGroup *group, CattaEntryGroupState state, void *userdata) {
36 meshlink_handle_t *mesh = userdata;
40 assert(mesh->catta_server != NULL);
41 assert(mesh->catta_poll != NULL);
43 pthread_mutex_lock(&(mesh->mesh_mutex));
45 /* Called whenever the entry group state changes */
47 case CATTA_ENTRY_GROUP_ESTABLISHED:
48 /* The entry group has been established successfully */
49 logger(mesh, MESHLINK_DEBUG, "Catta Service successfully established.\n");
52 case CATTA_ENTRY_GROUP_COLLISION:
53 logger(mesh, MESHLINK_WARNING, "Catta Service collision.\n");
54 // @TODO can we just set a new name and retry?
57 case CATTA_ENTRY_GROUP_FAILURE :
58 /* Some kind of failure happened while we were registering our services */
59 logger(mesh, MESHLINK_ERROR, "Catta Entry group failure: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
60 catta_simple_poll_quit(mesh->catta_poll);
63 case CATTA_ENTRY_GROUP_UNCOMMITED:
64 case CATTA_ENTRY_GROUP_REGISTERING:
68 pthread_mutex_unlock(&(mesh->mesh_mutex));
72 static void discovery_create_services(meshlink_handle_t *mesh) {
73 char *txt_name = NULL;
77 assert(mesh->name != NULL);
78 assert(mesh->myport != NULL);
79 assert(mesh->catta_server != NULL);
80 assert(mesh->catta_poll != NULL);
81 assert(mesh->catta_servicetype != NULL);
82 assert(mesh->self != NULL);
84 pthread_mutex_lock(&(mesh->mesh_mutex));
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) {
90 if(!(mesh->catta_group = catta_s_entry_group_new(mesh->catta_server, discovery_entry_group_callback, mesh))) {
91 logger(mesh, MESHLINK_ERROR, "catta_entry_group_new() failed: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
96 /* Create txt records */
97 size_t txt_name_len = sizeof(MESHLINK_MDNS_NAME_KEY) + 1 + strlen(mesh->name) + 1;
98 txt_name = malloc(txt_name_len);
100 if(txt_name == NULL) {
101 logger(mesh, MESHLINK_ERROR, "Could not allocate memory for TXT record\n");
105 snprintf(txt_name, txt_name_len, "%s=%s", MESHLINK_MDNS_NAME_KEY, mesh->name);
107 char txt_fingerprint[sizeof(MESHLINK_MDNS_FINGERPRINT_KEY) + 1 + MESHLINK_FINGERPRINTLEN + 1];
108 snprintf(txt_fingerprint, sizeof(txt_fingerprint), "%s=%s", MESHLINK_MDNS_FINGERPRINT_KEY, meshlink_get_fingerprint(mesh, (meshlink_node_t *)mesh->self));
110 /* Add the service */
113 if((ret = catta_server_add_service(mesh->catta_server, mesh->catta_group, CATTA_IF_UNSPEC, CATTA_PROTO_UNSPEC, 0, meshlink_get_fingerprint(mesh, (meshlink_node_t *)mesh->self), mesh->catta_servicetype, NULL, NULL, atoi(mesh->myport), txt_name, txt_fingerprint, NULL)) < 0) {
114 logger(mesh, MESHLINK_ERROR, "Failed to add service: %s\n", catta_strerror(ret));
118 /* Tell the server to register the service */
119 if((ret = catta_s_entry_group_commit(mesh->catta_group)) < 0) {
120 logger(mesh, MESHLINK_ERROR, "Failed to commit entry_group: %s\n", catta_strerror(ret));
127 catta_simple_poll_quit(mesh->catta_poll);
135 pthread_mutex_unlock(&(mesh->mesh_mutex));
138 static void discovery_server_callback(CattaServer *server, CattaServerState state, void *userdata) {
140 meshlink_handle_t *mesh = userdata;
143 assert(mesh != NULL);
146 case CATTA_SERVER_RUNNING:
148 /* The serve has startup successfully and registered its host
149 * name on the network, so it's time to create our services */
150 if(!mesh->catta_group) {
151 discovery_create_services(mesh);
156 case CATTA_SERVER_COLLISION: {
158 assert(mesh->catta_server != NULL);
159 assert(mesh->catta_poll != NULL);
161 /* A host name collision happened. Let's pick a new name for the server */
163 generate_rand_string(hostname, sizeof(hostname));
164 int result = catta_server_set_host_name(mesh->catta_server, hostname);
167 catta_simple_poll_quit(mesh->catta_poll);
172 case CATTA_SERVER_REGISTERING:
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;
184 case CATTA_SERVER_FAILURE:
186 assert(mesh->catta_server != NULL);
187 assert(mesh->catta_poll != NULL);
189 /* Terminate on failure */
190 catta_simple_poll_quit(mesh->catta_poll);
193 case CATTA_SERVER_INVALID:
198 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) {
202 meshlink_handle_t *mesh = userdata;
205 assert(resolver != NULL);
206 assert(mesh != NULL);
207 assert(mesh->catta_server != NULL);
209 /* Called whenever a service has been resolved successfully or timed out */
211 case CATTA_RESOLVER_FAILURE:
213 assert(name != NULL);
214 assert(type != NULL);
215 assert(domain != NULL);
218 case CATTA_RESOLVER_FOUND: {
220 assert(name != NULL);
221 assert(type != NULL);
222 assert(domain != NULL);
223 assert(host_name != NULL);
224 assert(address != NULL);
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 != NULL && node_fp_li != NULL) {
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 pthread_mutex_lock(&(mesh->mesh_mutex));
241 meshlink_node_t *node = meshlink_get_node(mesh, node_name);
244 logger(mesh, MESHLINK_INFO, "Node %s is part of the mesh network.\n", node->name);
247 memset(&naddress, 0, sizeof(naddress));
249 switch(address->proto) {
250 case CATTA_PROTO_INET: {
251 naddress.in.sin_family = AF_INET;
252 naddress.in.sin_port = htons(port);
253 naddress.in.sin_addr.s_addr = address->data.ipv4.address;
257 case CATTA_PROTO_INET6: {
258 naddress.in6.sin6_family = AF_INET6;
259 naddress.in6.sin6_port = htons(port);
260 memcpy(naddress.in6.sin6_addr.s6_addr, address->data.ipv6.address, sizeof(naddress.in6.sin6_addr.s6_addr));
265 naddress.unknown.family = AF_UNKNOWN;
269 if(naddress.unknown.family != AF_UNKNOWN) {
270 meshlink_hint_address(mesh, (meshlink_node_t *)node, (struct sockaddr *)&naddress);
271 pthread_mutex_lock(&(mesh->mesh_mutex));
273 node_t *n = (node_t *)node;
275 if(n->connection && n->connection->outgoing) {
276 n->connection->outgoing->timeout = 0;
278 if(n->connection->outgoing->ev.cb) {
279 timeout_set(&mesh->loop, &n->connection->outgoing->ev, &(struct timeval) {
284 n->connection->last_ping_time = 0;
287 pthread_mutex_unlock(&(mesh->mesh_mutex));
289 logger(mesh, MESHLINK_WARNING, "Could not resolve node %s to a known address family type.\n", node->name);
292 logger(mesh, MESHLINK_WARNING, "Node %s is not part of the mesh network.\n", node_name);
295 pthread_mutex_unlock(&(mesh->mesh_mutex));
302 catta_s_service_resolver_free(resolver);
305 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) {
308 meshlink_handle_t *mesh = userdata;
311 assert(mesh != NULL);
312 assert(mesh->catta_server != NULL);
313 assert(mesh->catta_poll != NULL);
315 /* Called whenever a new services becomes available on the LAN or is removed from the LAN */
317 case CATTA_BROWSER_FAILURE:
318 catta_simple_poll_quit(mesh->catta_poll);
321 case CATTA_BROWSER_NEW:
322 catta_s_service_resolver_new(mesh->catta_server, interface_, protocol, name, type, domain, CATTA_PROTO_UNSPEC, 0, discovery_resolve_callback, mesh);
325 case CATTA_BROWSER_REMOVE:
326 case CATTA_BROWSER_ALL_FOR_NOW:
327 case CATTA_BROWSER_CACHE_EXHAUSTED:
332 static void *discovery_loop(void *userdata) {
333 meshlink_handle_t *mesh = userdata;
336 assert(mesh != NULL);
337 assert(mesh->catta_poll != NULL);
339 catta_simple_poll_loop(mesh->catta_poll);
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 bool discovery_start(meshlink_handle_t *mesh) {
371 logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
374 assert(mesh != NULL);
375 assert(mesh->catta_poll == NULL);
376 assert(mesh->catta_server == NULL);
377 assert(mesh->catta_browser == NULL);
378 assert(mesh->discovery_threadstarted == false);
379 assert(mesh->catta_servicetype == NULL);
382 catta_set_log_function(discovery_log_cb);
384 // create service type string
385 size_t servicetype_strlen = sizeof(MESHLINK_MDNS_SERVICE_TYPE) + strlen(mesh->appname) + 1;
386 mesh->catta_servicetype = malloc(servicetype_strlen);
388 if(mesh->catta_servicetype == NULL) {
389 logger(mesh, MESHLINK_ERROR, "Failed to allocate memory for service type string.\n");
393 snprintf(mesh->catta_servicetype, servicetype_strlen, MESHLINK_MDNS_SERVICE_TYPE, mesh->appname);
395 // Allocate discovery loop object
396 if(!(mesh->catta_poll = catta_simple_poll_new())) {
397 logger(mesh, MESHLINK_ERROR, "Failed to create discovery poll object.\n");
401 // generate some unique host name (we actually do not care about it)
403 generate_rand_string(hostname, sizeof(hostname));
405 // Let's set the host name for this server.
406 CattaServerConfig config;
407 catta_server_config_init(&config);
408 config.host_name = catta_strdup(hostname);
409 config.publish_workstation = 0;
410 config.disallow_other_stacks = 0;
411 config.publish_hinfo = 0;
412 config.publish_addresses = 1;
413 config.publish_no_reverse = 1;
415 /* Allocate a new server */
417 mesh->catta_server = catta_server_new(catta_simple_poll_get(mesh->catta_poll), &config, discovery_server_callback, mesh, &error);
419 /* Free the configuration data */
420 catta_server_config_free(&config);
422 /* Check wether creating the server object succeeded */
423 if(!mesh->catta_server) {
424 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
428 // Create the service browser
429 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))) {
430 logger(mesh, MESHLINK_ERROR, "Failed to create discovery service browser: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
434 // Start the discovery thread
435 if(pthread_create(&mesh->discovery_thread, NULL, discovery_loop, mesh) != 0) {
436 logger(mesh, MESHLINK_ERROR, "Could not start discovery thread: %s\n", strerror(errno));
437 memset(&mesh->discovery_thread, 0, sizeof(mesh)->discovery_thread);
441 mesh->discovery_threadstarted = true;
447 if(mesh->catta_browser != NULL) {
448 catta_s_service_browser_free(mesh->catta_browser);
449 mesh->catta_browser = NULL;
452 if(mesh->catta_server != NULL) {
453 catta_server_free(mesh->catta_server);
454 mesh->catta_server = NULL;
457 if(mesh->catta_poll != NULL) {
458 catta_simple_poll_free(mesh->catta_poll);
459 mesh->catta_poll = NULL;
462 if(mesh->catta_servicetype != NULL) {
463 free(mesh->catta_servicetype);
464 mesh->catta_servicetype = NULL;
470 void discovery_stop(meshlink_handle_t *mesh) {
471 logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
474 assert(mesh != NULL);
477 if(mesh->catta_poll) {
478 catta_simple_poll_quit(mesh->catta_poll);
481 // Wait for the discovery thread to finish
482 if(mesh->discovery_threadstarted == true) {
483 pthread_join(mesh->discovery_thread, NULL);
484 mesh->discovery_threadstarted = false;
487 // Clean up resources
488 if(mesh->catta_browser != NULL) {
489 catta_s_service_browser_free(mesh->catta_browser);
490 mesh->catta_browser = NULL;
493 if(mesh->catta_group) {
494 catta_s_entry_group_reset(mesh->catta_group);
495 catta_s_entry_group_free(mesh->catta_group);
496 mesh->catta_group = NULL;
499 if(mesh->catta_server != NULL) {
500 catta_server_free(mesh->catta_server);
501 mesh->catta_server = NULL;
504 if(mesh->catta_poll != NULL) {
505 catta_simple_poll_free(mesh->catta_poll);
506 mesh->catta_poll = NULL;
509 if(mesh->catta_servicetype != NULL) {
510 free(mesh->catta_servicetype);
511 mesh->catta_servicetype = NULL;