]> git.meshlink.io Git - meshlink/blob - src/discovery.c
Run Catta in the same network namespace as MeshLink.
[meshlink] / src / discovery.c
1 #include "system.h"
2
3 #include <catta/core.h>
4 #include <catta/lookup.h>
5 #include <catta/publish.h>
6 #include <catta/log.h>
7 #include <catta/simple-watch.h>
8 #include <catta/malloc.h>
9 #include <catta/alternative.h>
10 #include <catta/error.h>
11
12 #include "meshlink_internal.h"
13 #include "discovery.h"
14 #include "sockaddr.h"
15 #include "logger.h"
16 #include "node.h"
17 #include "connection.h"
18 #include "xalloc.h"
19
20 #define MESHLINK_MDNS_SERVICE_TYPE "_%s._tcp"
21 #define MESHLINK_MDNS_NAME_KEY "name"
22 #define MESHLINK_MDNS_FINGERPRINT_KEY "fingerprint"
23
24 static void generate_rand_string(char *buffer, size_t size) {
25         for(size_t i = 0; i < (size - 1); ++i) {
26                 buffer[i] = 'a' + (rand() % ('z' - 'a' + 1));
27         }
28
29         buffer[size - 1] = '\0';
30 }
31
32 static void discovery_entry_group_callback(CattaServer *server, CattaSEntryGroup *group, CattaEntryGroupState state, void *userdata) {
33         (void)server;
34         (void)group;
35         meshlink_handle_t *mesh = userdata;
36
37         // asserts
38         assert(mesh != NULL);
39         assert(mesh->catta_server != NULL);
40         assert(mesh->catta_poll != NULL);
41
42         /* Called whenever the entry group state changes */
43         switch(state) {
44         case CATTA_ENTRY_GROUP_ESTABLISHED:
45                 /* The entry group has been established successfully */
46                 logger(mesh, MESHLINK_DEBUG, "Catta Service successfully established.\n");
47                 break;
48
49         case CATTA_ENTRY_GROUP_COLLISION:
50                 logger(mesh, MESHLINK_WARNING, "Catta Service collision.\n");
51                 // @TODO can we just set a new name and retry?
52                 break;
53
54         case CATTA_ENTRY_GROUP_FAILURE :
55                 /* Some kind of failure happened while we were registering our services */
56                 logger(mesh, MESHLINK_ERROR, "Catta Entry group failure: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
57                 catta_simple_poll_quit(mesh->catta_poll);
58                 break;
59
60         case CATTA_ENTRY_GROUP_UNCOMMITED:
61         case CATTA_ENTRY_GROUP_REGISTERING:
62                 break;
63         }
64 }
65
66
67 static void discovery_create_services(meshlink_handle_t *mesh) {
68         char *fingerprint = NULL;
69         char *txt_name = NULL;
70         char *txt_fingerprint = NULL;
71
72         // asserts
73         assert(mesh != NULL);
74         assert(mesh->name != NULL);
75         assert(mesh->myport != NULL);
76         assert(mesh->catta_server != NULL);
77         assert(mesh->catta_poll != NULL);
78         assert(mesh->catta_servicetype != NULL);
79         assert(mesh->self != NULL);
80
81         pthread_mutex_lock(&(mesh->mesh_mutex));
82
83         logger(mesh, MESHLINK_DEBUG, "Adding service\n");
84
85         /* Ifthis is the first time we're called, let's create a new entry group */
86         if(!mesh->catta_group) {
87                 if(!(mesh->catta_group = catta_s_entry_group_new(mesh->catta_server, discovery_entry_group_callback, mesh))) {
88                         logger(mesh, MESHLINK_ERROR, "catta_entry_group_new() failed: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
89                         goto fail;
90                 }
91         }
92
93         /* Create txt records */
94         fingerprint = meshlink_get_fingerprint(mesh, (meshlink_node_t *)mesh->self);
95         xasprintf(&txt_name, "%s=%s", MESHLINK_MDNS_NAME_KEY, mesh->name);
96         xasprintf(&txt_fingerprint, "%s=%s", MESHLINK_MDNS_FINGERPRINT_KEY, fingerprint);
97
98         /* Add the service */
99         int ret = 0;
100
101         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) {
102                 logger(mesh, MESHLINK_ERROR, "Failed to add service: %s\n", catta_strerror(ret));
103                 goto fail;
104         }
105
106         /* Tell the server to register the service */
107         if((ret = catta_s_entry_group_commit(mesh->catta_group)) < 0) {
108                 logger(mesh, MESHLINK_ERROR, "Failed to commit entry_group: %s\n", catta_strerror(ret));
109                 goto fail;
110         }
111
112         goto done;
113
114 fail:
115         catta_simple_poll_quit(mesh->catta_poll);
116
117 done:
118         free(fingerprint);
119         free(txt_name);
120         free(txt_fingerprint);
121
122         pthread_mutex_unlock(&(mesh->mesh_mutex));
123 }
124
125 static void discovery_server_callback(CattaServer *server, CattaServerState state, void *userdata) {
126         (void)server;
127         meshlink_handle_t *mesh = userdata;
128
129         // asserts
130         assert(mesh != NULL);
131
132         switch(state) {
133         case CATTA_SERVER_RUNNING:
134
135                 /* The serve has startup successfully and registered its host
136                  * name on the network, so it's time to create our services */
137                 if(!mesh->catta_group) {
138                         discovery_create_services(mesh);
139                 }
140
141                 break;
142
143         case CATTA_SERVER_COLLISION: {
144                 // asserts
145                 assert(mesh->catta_server != NULL);
146                 assert(mesh->catta_poll != NULL);
147
148                 /* A host name collision happened. Let's pick a new name for the server */
149                 char hostname[17];
150                 generate_rand_string(hostname, sizeof(hostname));
151                 int result = catta_server_set_host_name(mesh->catta_server, hostname);
152
153                 if(result < 0) {
154                         catta_simple_poll_quit(mesh->catta_poll);
155                 }
156         }
157         break;
158
159         case CATTA_SERVER_REGISTERING:
160
161                 /* Let's drop our registered services. When the server is back
162                  * in CATTA_SERVER_RUNNING state we will register them
163                  * again with the new host name. */
164                 if(mesh->catta_group) {
165                         catta_s_entry_group_reset(mesh->catta_group);
166                         mesh->catta_group = NULL;
167                 }
168
169                 break;
170
171         case CATTA_SERVER_FAILURE:
172                 // asserts
173                 assert(mesh->catta_server != NULL);
174                 assert(mesh->catta_poll != NULL);
175
176                 /* Terminate on failure */
177                 catta_simple_poll_quit(mesh->catta_poll);
178                 break;
179
180         case CATTA_SERVER_INVALID:
181                 break;
182         }
183 }
184
185 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) {
186         (void)interface_;
187         (void)protocol;
188         (void)flags;
189         meshlink_handle_t *mesh = userdata;
190
191         // asserts
192         assert(resolver != NULL);
193         assert(mesh != NULL);
194         assert(mesh->catta_server != NULL);
195
196         /* Called whenever a service has been resolved successfully or timed out */
197         switch(event) {
198         case CATTA_RESOLVER_FAILURE:
199                 // asserts
200                 assert(name != NULL);
201                 assert(type != NULL);
202                 assert(domain != NULL);
203                 break;
204
205         case CATTA_RESOLVER_FOUND: {
206                 // asserts
207                 assert(name != NULL);
208                 assert(type != NULL);
209                 assert(domain != NULL);
210                 assert(host_name != NULL);
211                 assert(address != NULL);
212                 assert(txt != NULL);
213
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);
217
218                 if(node_name_li != NULL && node_fp_li != NULL) {
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);
221
222                         if(node_name[0] == '=' && node_fp[0] == '=') {
223                                 pthread_mutex_lock(&(mesh->mesh_mutex));
224
225                                 node_name += 1;
226                                 node_fp += 1;
227
228                                 meshlink_node_t *node = meshlink_get_node(mesh, node_name);
229
230                                 if(node != NULL) {
231                                         logger(mesh, MESHLINK_INFO, "Node %s is part of the mesh network.\n", node->name);
232
233                                         sockaddr_t naddress;
234                                         memset(&naddress, 0, sizeof(naddress));
235
236                                         switch(address->proto) {
237                                         case CATTA_PROTO_INET: {
238                                                 naddress.in.sin_family = AF_INET;
239                                                 naddress.in.sin_port = htons(port);
240                                                 naddress.in.sin_addr.s_addr = address->data.ipv4.address;
241                                         }
242                                         break;
243
244                                         case CATTA_PROTO_INET6: {
245                                                 naddress.in6.sin6_family = AF_INET6;
246                                                 naddress.in6.sin6_port = htons(port);
247                                                 memcpy(naddress.in6.sin6_addr.s6_addr, address->data.ipv6.address, sizeof(naddress.in6.sin6_addr.s6_addr));
248                                         }
249                                         break;
250
251                                         default:
252                                                 naddress.unknown.family = AF_UNKNOWN;
253                                                 break;
254                                         }
255
256                                         if(naddress.unknown.family != AF_UNKNOWN) {
257                                                 meshlink_hint_address(mesh, (meshlink_node_t *)node, (struct sockaddr *)&naddress);
258
259                                                 node_t *n = (node_t *)node;
260
261                                                 if(n->connection && n->connection->outgoing) {
262                                                         n->connection->outgoing->timeout = 0;
263
264                                                         if(n->connection->outgoing->ev.cb) {
265                                                                 timeout_set(&mesh->loop, &n->connection->outgoing->ev, &(struct timeval) {
266                                                                         0, 0
267                                                                 });
268                                                         }
269
270                                                         n->connection->last_ping_time = 0;
271                                                 }
272
273                                         } else {
274                                                 logger(mesh, MESHLINK_WARNING, "Could not resolve node %s to a known address family type.\n", node->name);
275                                         }
276                                 } else {
277                                         logger(mesh, MESHLINK_WARNING, "Node %s is not part of the mesh network.\n", node_name);
278                                 }
279
280                                 pthread_mutex_unlock(&(mesh->mesh_mutex));
281                         }
282                 }
283         }
284         break;
285         }
286
287         catta_s_service_resolver_free(resolver);
288 }
289
290 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         (void)browser;
292         (void)flags;
293         meshlink_handle_t *mesh = userdata;
294
295         // asserts
296         assert(mesh != NULL);
297         assert(mesh->catta_server != NULL);
298         assert(mesh->catta_poll != NULL);
299
300         /* Called whenever a new services becomes available on the LAN or is removed from the LAN */
301         switch(event) {
302         case CATTA_BROWSER_FAILURE:
303                 catta_simple_poll_quit(mesh->catta_poll);
304                 break;
305
306         case CATTA_BROWSER_NEW:
307                 catta_s_service_resolver_new(mesh->catta_server, interface_, protocol, name, type, domain, CATTA_PROTO_UNSPEC, 0, discovery_resolve_callback, mesh);
308                 pthread_mutex_lock(&mesh->mesh_mutex);
309                 handle_network_change(mesh, ++mesh->catta_interfaces);
310                 pthread_mutex_unlock(&mesh->mesh_mutex);
311                 break;
312
313         case CATTA_BROWSER_REMOVE:
314                 pthread_mutex_lock(&mesh->mesh_mutex);
315                 handle_network_change(mesh, --mesh->catta_interfaces);
316                 pthread_mutex_unlock(&mesh->mesh_mutex);
317                 break;
318
319         case CATTA_BROWSER_ALL_FOR_NOW:
320         case CATTA_BROWSER_CACHE_EXHAUSTED:
321                 break;
322         }
323 }
324
325 static void discovery_log_cb(CattaLogLevel level, const char *txt) {
326         meshlink_log_level_t mlevel = MESHLINK_CRITICAL;
327
328         switch(level) {
329         case CATTA_LOG_ERROR:
330                 mlevel = MESHLINK_ERROR;
331                 break;
332
333         case CATTA_LOG_WARN:
334                 mlevel = MESHLINK_WARNING;
335                 break;
336
337         case CATTA_LOG_NOTICE:
338         case CATTA_LOG_INFO:
339                 mlevel = MESHLINK_INFO;
340                 break;
341
342         case CATTA_LOG_DEBUG:
343         default:
344                 mlevel = MESHLINK_DEBUG;
345                 break;
346         }
347
348         logger(NULL, mlevel, "%s\n", txt);
349 }
350
351 static void *discovery_loop(void *userdata) {
352         meshlink_handle_t *mesh = userdata;
353         assert(mesh != NULL);
354
355         // handle catta logs
356         catta_set_log_function(discovery_log_cb);
357
358         // create service type string
359         size_t servicetype_strlen = sizeof(MESHLINK_MDNS_SERVICE_TYPE) + strlen(mesh->appname) + 1;
360         mesh->catta_servicetype = malloc(servicetype_strlen);
361
362         if(mesh->catta_servicetype == NULL) {
363                 logger(mesh, MESHLINK_ERROR, "Failed to allocate memory for service type string.\n");
364                 goto fail;
365         }
366
367         snprintf(mesh->catta_servicetype, servicetype_strlen, MESHLINK_MDNS_SERVICE_TYPE, mesh->appname);
368
369         // Allocate discovery loop object
370         if(!(mesh->catta_poll = catta_simple_poll_new())) {
371                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery poll object.\n");
372                 goto fail;
373         }
374
375         // generate some unique host name (we actually do not care about it)
376         char hostname[17];
377         generate_rand_string(hostname, sizeof(hostname));
378
379         // Let's set the host name for this server.
380         CattaServerConfig config;
381         catta_server_config_init(&config);
382         config.host_name = catta_strdup(hostname);
383         config.publish_workstation = 0;
384         config.disallow_other_stacks = 0;
385         config.publish_hinfo = 0;
386         config.publish_addresses = 1;
387         config.publish_no_reverse = 1;
388
389         /* Allocate a new server */
390         int error;
391         mesh->catta_server = catta_server_new(catta_simple_poll_get(mesh->catta_poll), &config, discovery_server_callback, mesh, &error);
392
393         /* Free the configuration data */
394         catta_server_config_free(&config);
395
396         /* Check wether creating the server object succeeded */
397         if(!mesh->catta_server) {
398                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
399                 goto fail;
400         }
401
402         // Create the service browser
403         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))) {
404                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery service browser: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
405                 goto fail;
406         }
407
408         catta_simple_poll_loop(mesh->catta_poll);
409
410 fail:
411
412         if(mesh->catta_browser != NULL) {
413                 catta_s_service_browser_free(mesh->catta_browser);
414                 mesh->catta_browser = NULL;
415         }
416
417         if(mesh->catta_group) {
418                 catta_s_entry_group_reset(mesh->catta_group);
419                 catta_s_entry_group_free(mesh->catta_group);
420                 mesh->catta_group = NULL;
421         }
422
423         if(mesh->catta_server != NULL) {
424                 catta_server_free(mesh->catta_server);
425                 mesh->catta_server = NULL;
426         }
427
428         if(mesh->catta_poll != NULL) {
429                 catta_simple_poll_free(mesh->catta_poll);
430                 mesh->catta_poll = NULL;
431         }
432
433         if(mesh->catta_servicetype != NULL) {
434                 free(mesh->catta_servicetype);
435                 mesh->catta_servicetype = NULL;
436         }
437
438         return NULL;
439 }
440
441 bool discovery_start(meshlink_handle_t *mesh) {
442         logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
443
444         // asserts
445         assert(mesh != NULL);
446         assert(mesh->catta_poll == NULL);
447         assert(mesh->catta_server == NULL);
448         assert(mesh->catta_browser == NULL);
449         assert(mesh->discovery_threadstarted == false);
450         assert(mesh->catta_servicetype == NULL);
451
452         // Start the discovery thread
453         if(pthread_create(&mesh->discovery_thread, NULL, discovery_loop, mesh) != 0) {
454                 logger(mesh, MESHLINK_ERROR, "Could not start discovery thread: %s\n", strerror(errno));
455                 memset(&mesh->discovery_thread, 0, sizeof(mesh)->discovery_thread);
456                 return false;
457         }
458
459         mesh->discovery_threadstarted = true;
460
461         return true;
462 }
463
464 void discovery_stop(meshlink_handle_t *mesh) {
465         logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
466
467         // asserts
468         assert(mesh != NULL);
469
470         // Shut down
471         if(mesh->catta_poll) {
472                 catta_simple_poll_quit(mesh->catta_poll);
473         }
474
475         // Wait for the discovery thread to finish
476         if(mesh->discovery_threadstarted == true) {
477                 pthread_join(mesh->discovery_thread, NULL);
478                 mesh->discovery_threadstarted = false;
479         }
480
481         mesh->catta_interfaces = 0;
482 }