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:
132 /* The serve has startup successfully and registered its host
133 * name on the network, so it's time to create our services */
134 assert(pthread_mutex_lock(&mesh->mutex) == 0);
136 if(!mesh->catta_group) {
137 discovery_create_services(mesh);
140 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
144 case CATTA_SERVER_COLLISION: {
145 /* A host name collision happened. Let's pick a new name for the server */
147 generate_rand_string(mesh, hostname, sizeof(hostname));
149 assert(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 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
164 case CATTA_SERVER_REGISTERING:
165 assert(pthread_mutex_lock(&mesh->mutex) == 0);
167 /* Let's drop our registered services. When the server is back
168 * in CATTA_SERVER_RUNNING state we will register them
169 * again with the new host name. */
170 if(mesh->catta_group) {
171 catta_s_entry_group_reset(mesh->catta_group);
172 mesh->catta_group = NULL;
175 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
179 case CATTA_SERVER_FAILURE:
180 assert(pthread_mutex_lock(&mesh->mutex) == 0);
182 assert(mesh->catta_server);
183 assert(mesh->catta_poll);
185 /* Terminate on failure */
186 catta_simple_poll_quit(mesh->catta_poll);
188 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
191 case CATTA_SERVER_INVALID:
196 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) {
205 meshlink_handle_t *mesh = userdata;
209 if(event != CATTA_RESOLVER_FOUND) {
210 catta_s_service_resolver_free(resolver);
214 // retrieve fingerprint
215 CattaStringList *node_name_li = catta_string_list_find(txt, MESHLINK_MDNS_NAME_KEY);
216 CattaStringList *node_fp_li = catta_string_list_find(txt, MESHLINK_MDNS_FINGERPRINT_KEY);
218 if(node_name_li && node_fp_li) {
219 char *node_name = (char *)catta_string_list_get_text(node_name_li) + strlen(MESHLINK_MDNS_NAME_KEY);
220 char *node_fp = (char *)catta_string_list_get_text(node_fp_li) + strlen(MESHLINK_MDNS_FINGERPRINT_KEY);
222 if(node_name[0] == '=' && node_fp[0] == '=') {
223 assert(pthread_mutex_lock(&mesh->mutex) == 0);
227 meshlink_node_t *node = meshlink_get_node(mesh, node_name);
230 logger(mesh, MESHLINK_INFO, "Node %s is part of the mesh network.\n", node->name);
233 memset(&naddress, 0, sizeof(naddress));
235 switch(address->proto) {
236 case CATTA_PROTO_INET: {
237 naddress.in.sin_family = AF_INET;
238 naddress.in.sin_port = htons(port);
239 naddress.in.sin_addr.s_addr = address->data.ipv4.address;
243 case CATTA_PROTO_INET6: {
244 naddress.in6.sin6_family = AF_INET6;
245 naddress.in6.sin6_port = htons(port);
246 memcpy(naddress.in6.sin6_addr.s6_addr, address->data.ipv6.address, sizeof(naddress.in6.sin6_addr.s6_addr));
251 naddress.unknown.family = AF_UNKNOWN;
255 if(naddress.unknown.family != AF_UNKNOWN) {
256 node_t *n = (node_t *)node;
257 connection_t *c = n->connection;
259 n->catta_address = naddress;
260 node_add_recent_address(mesh, n, &naddress);
262 if(c && c->outgoing && !c->status.active) {
263 c->outgoing->timeout = 0;
265 if(c->outgoing->ev.cb) {
266 timeout_set(&mesh->loop, &c->outgoing->ev, &(struct timespec) {
271 c->last_ping_time = -3600;
275 logger(mesh, MESHLINK_WARNING, "Could not resolve node %s to a known address family type.\n", node->name);
278 logger(mesh, MESHLINK_WARNING, "Node %s is not part of the mesh network.\n", node_name);
281 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
285 catta_s_service_resolver_free(resolver);
288 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) {
291 meshlink_handle_t *mesh = userdata;
293 /* Called whenever a new services becomes available on the LAN or is removed from the LAN */
295 case CATTA_BROWSER_FAILURE:
296 assert(pthread_mutex_lock(&mesh->mutex) == 0);
297 catta_simple_poll_quit(mesh->catta_poll);
298 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
301 case CATTA_BROWSER_NEW:
302 assert(pthread_mutex_lock(&mesh->mutex) == 0);
303 catta_s_service_resolver_new(mesh->catta_server, interface_, protocol, name, type, domain, CATTA_PROTO_UNSPEC, 0, discovery_resolve_callback, mesh);
304 handle_network_change(mesh, ++mesh->catta_interfaces);
305 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
308 case CATTA_BROWSER_REMOVE:
309 assert(pthread_mutex_lock(&mesh->mutex) == 0);
310 handle_network_change(mesh, --mesh->catta_interfaces);
311 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
314 case CATTA_BROWSER_ALL_FOR_NOW:
315 case CATTA_BROWSER_CACHE_EXHAUSTED:
320 static void discovery_log_cb(CattaLogLevel level, const char *txt) {
321 meshlink_log_level_t mlevel = MESHLINK_CRITICAL;
324 case CATTA_LOG_ERROR:
325 mlevel = MESHLINK_ERROR;
329 mlevel = MESHLINK_WARNING;
332 case CATTA_LOG_NOTICE:
334 mlevel = MESHLINK_INFO;
337 case CATTA_LOG_DEBUG:
339 mlevel = MESHLINK_DEBUG;
343 logger(NULL, mlevel, "%s\n", txt);
346 static void *discovery_loop(void *userdata) {
348 meshlink_handle_t *mesh = userdata;
351 assert(pthread_mutex_lock(&mesh->discovery_mutex) == 0);
354 catta_set_log_function(discovery_log_cb);
356 // create service type string
357 char appname[strlen(mesh->appname) + 2];
358 strcpy(appname, mesh->appname);
360 for(char *p = appname; *p; p++) {
361 if(!isalnum(*p) && *p != '_' && *p != '-') {
371 size_t servicetype_strlen = sizeof(MESHLINK_MDNS_SERVICE_TYPE) + strlen(appname) + 1;
372 mesh->catta_servicetype = malloc(servicetype_strlen);
374 if(mesh->catta_servicetype == NULL) {
375 logger(mesh, MESHLINK_ERROR, "Failed to allocate memory for service type string.\n");
379 snprintf(mesh->catta_servicetype, servicetype_strlen, MESHLINK_MDNS_SERVICE_TYPE, appname);
381 // Allocate discovery loop object
382 if(!(mesh->catta_poll = catta_simple_poll_new())) {
383 logger(mesh, MESHLINK_ERROR, "Failed to create discovery poll object.\n");
387 // generate some unique host name (we actually do not care about it)
389 generate_rand_string(mesh, hostname, sizeof(hostname));
391 // Let's set the host name for this server.
392 CattaServerConfig config;
393 catta_server_config_init(&config);
394 config.host_name = catta_strdup(hostname);
395 config.publish_workstation = 0;
396 config.disallow_other_stacks = 0;
397 config.publish_hinfo = 0;
398 config.publish_addresses = 1;
399 config.publish_no_reverse = 1;
400 config.allow_point_to_point = 1;
402 /* Allocate a new server */
404 mesh->catta_server = catta_server_new(catta_simple_poll_get(mesh->catta_poll), &config, discovery_server_callback, mesh, &error);
406 /* Free the configuration data */
407 catta_server_config_free(&config);
409 /* Check whether creating the server object succeeded */
410 if(!mesh->catta_server) {
411 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
415 // Create the service browser
416 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))) {
417 logger(mesh, MESHLINK_ERROR, "Failed to create discovery service browser: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
425 assert(pthread_cond_broadcast(&mesh->discovery_cond) == 0);
426 assert(pthread_mutex_unlock(&mesh->discovery_mutex) == 0);
429 catta_simple_poll_loop(mesh->catta_poll);
432 if(mesh->catta_browser) {
433 catta_s_service_browser_free(mesh->catta_browser);
434 mesh->catta_browser = NULL;
437 if(mesh->catta_group) {
438 catta_s_entry_group_reset(mesh->catta_group);
439 catta_s_entry_group_free(mesh->catta_group);
440 mesh->catta_group = NULL;
443 if(mesh->catta_server) {
444 catta_server_free(mesh->catta_server);
445 mesh->catta_server = NULL;
448 if(mesh->catta_poll) {
449 catta_simple_poll_free(mesh->catta_poll);
450 mesh->catta_poll = NULL;
453 if(mesh->catta_servicetype) {
454 free(mesh->catta_servicetype);
455 mesh->catta_servicetype = NULL;
462 static void pfroute_io_handler(event_loop_t *loop, void *data, int flags) {
464 static time_t prev_update;
465 meshlink_handle_t *mesh = data;
468 struct rt_msghdr rtm;
473 msg.rtm.rtm_version = 0;
474 ssize_t result = recv(mesh->pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
477 if(result == 0 || errno == EAGAIN || errno == EINTR) {
481 logger(mesh, MESHLINK_ERROR, "Reading from PFROUTE socket failed: %s\n", strerror(errno));
482 io_set(loop, &mesh->pfroute_io, 0);
485 if(msg.rtm.rtm_version != RTM_VERSION) {
486 logger(mesh, MESHLINK_ERROR, "Invalid PFROUTE message version\n");
490 switch(msg.rtm.rtm_type) {
494 if(loop->now.tv_sec > prev_update + 5) {
495 prev_update = loop->now.tv_sec;
496 handle_network_change(mesh, 1);
508 bool discovery_start(meshlink_handle_t *mesh) {
509 logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
512 assert(!mesh->catta_poll);
513 assert(!mesh->catta_server);
514 assert(!mesh->catta_browser);
515 assert(!mesh->discovery_threadstarted);
516 assert(!mesh->catta_servicetype);
518 assert(pthread_mutex_lock(&mesh->discovery_mutex) == 0);
520 // Start the discovery thread
521 if(pthread_create(&mesh->discovery_thread, NULL, discovery_loop, mesh) != 0) {
522 assert(pthread_mutex_unlock(&mesh->discovery_mutex) == 0);
523 logger(mesh, MESHLINK_ERROR, "Could not start discovery thread: %s\n", strerror(errno));
524 memset(&mesh->discovery_thread, 0, sizeof(mesh)->discovery_thread);
528 assert(pthread_cond_wait(&mesh->discovery_cond, &mesh->discovery_mutex) == 0);
529 assert(pthread_mutex_unlock(&mesh->discovery_mutex) == 0);
531 mesh->discovery_threadstarted = true;
534 int sock = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
537 io_add(&mesh->loop, &mesh->pfroute_io, pfroute_io_handler, mesh, sock, IO_READ);
539 logger(mesh, MESHLINK_WARNING, "Could not open PF_ROUTE socket: %s", strerror(errno));
547 void discovery_stop(meshlink_handle_t *mesh) {
548 logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
554 if(mesh->pfroute_io.cb) {
555 close(mesh->pfroute_io.fd);
556 io_del(&mesh->loop, &mesh->pfroute_io);
562 if(mesh->catta_poll) {
563 catta_simple_poll_quit(mesh->catta_poll);
566 // Wait for the discovery thread to finish
567 if(mesh->discovery_threadstarted == true) {
568 assert(pthread_join(mesh->discovery_thread, NULL) == 0);
569 mesh->discovery_threadstarted = false;
572 mesh->catta_interfaces = 0;