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