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