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