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