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