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