]> 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
133                 /* The serve has startup successfully and registered its host
134                  * name on the network, so it's time to create our services */
135                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
136                         abort();
137                 }
138
139                 if(!mesh->catta_group) {
140                         discovery_create_services(mesh);
141                 }
142
143                 pthread_mutex_unlock(&mesh->mutex);
144
145                 break;
146
147         case CATTA_SERVER_COLLISION: {
148                 /* A host name collision happened. Let's pick a new name for the server */
149                 char hostname[17];
150                 generate_rand_string(mesh, hostname, sizeof(hostname));
151
152                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
153                         abort();
154                 }
155
156                 assert(mesh->catta_server);
157                 assert(mesh->catta_poll);
158
159                 int result = catta_server_set_host_name(mesh->catta_server, hostname);
160
161                 if(result < 0) {
162                         catta_simple_poll_quit(mesh->catta_poll);
163                 }
164
165                 pthread_mutex_unlock(&mesh->mutex);
166         }
167         break;
168
169         case CATTA_SERVER_REGISTERING:
170                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
171                         abort();
172                 }
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                 pthread_mutex_unlock(&mesh->mutex);
183
184                 break;
185
186         case CATTA_SERVER_FAILURE:
187                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
188                         abort();
189                 }
190
191                 assert(mesh->catta_server);
192                 assert(mesh->catta_poll);
193
194                 /* Terminate on failure */
195                 catta_simple_poll_quit(mesh->catta_poll);
196
197                 pthread_mutex_unlock(&mesh->mutex);
198                 break;
199
200         case CATTA_SERVER_INVALID:
201                 break;
202         }
203 }
204
205 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) {
206         (void)interface_;
207         (void)protocol;
208         (void)flags;
209         (void)name;
210         (void)type;
211         (void)domain;
212         (void)host_name;
213
214         meshlink_handle_t *mesh = userdata;
215
216         assert(mesh);
217
218         if(event != CATTA_RESOLVER_FOUND) {
219                 catta_s_service_resolver_free(resolver);
220                 return;
221         }
222
223         // retrieve fingerprint
224         CattaStringList *node_name_li = catta_string_list_find(txt, MESHLINK_MDNS_NAME_KEY);
225         CattaStringList *node_fp_li = catta_string_list_find(txt, MESHLINK_MDNS_FINGERPRINT_KEY);
226
227         if(node_name_li && node_fp_li) {
228                 char *node_name = (char *)catta_string_list_get_text(node_name_li) + strlen(MESHLINK_MDNS_NAME_KEY);
229                 char *node_fp = (char *)catta_string_list_get_text(node_fp_li) + strlen(MESHLINK_MDNS_FINGERPRINT_KEY);
230
231                 if(node_name[0] == '=' && node_fp[0] == '=') {
232                         if(pthread_mutex_lock(&mesh->mutex) != 0) {
233                                 abort();
234                         }
235
236                         node_name += 1;
237
238                         meshlink_node_t *node = meshlink_get_node(mesh, node_name);
239
240                         if(node) {
241                                 logger(mesh, MESHLINK_INFO, "Node %s is part of the mesh network.\n", node->name);
242
243                                 sockaddr_t naddress;
244                                 memset(&naddress, 0, sizeof(naddress));
245
246                                 switch(address->proto) {
247                                 case CATTA_PROTO_INET: {
248                                         naddress.in.sin_family = AF_INET;
249                                         naddress.in.sin_port = htons(port);
250                                         naddress.in.sin_addr.s_addr = address->data.ipv4.address;
251                                 }
252                                 break;
253
254                                 case CATTA_PROTO_INET6: {
255                                         naddress.in6.sin6_family = AF_INET6;
256                                         naddress.in6.sin6_port = htons(port);
257                                         memcpy(naddress.in6.sin6_addr.s6_addr, address->data.ipv6.address, sizeof(naddress.in6.sin6_addr.s6_addr));
258                                 }
259                                 break;
260
261                                 default:
262                                         naddress.unknown.family = AF_UNKNOWN;
263                                         break;
264                                 }
265
266                                 if(naddress.unknown.family != AF_UNKNOWN) {
267                                         node_t *n = (node_t *)node;
268                                         connection_t *c = n->connection;
269
270                                         n->catta_address = naddress;
271                                         node_add_recent_address(mesh, n, &naddress);
272
273                                         if(c && c->outgoing && !c->status.active) {
274                                                 c->outgoing->timeout = 0;
275
276                                                 if(c->outgoing->ev.cb) {
277                                                         timeout_set(&mesh->loop, &c->outgoing->ev, &(struct timespec) {
278                                                                 0, 0
279                                                         });
280                                                 }
281
282                                                 c->last_ping_time = -3600;
283                                         }
284
285                                 } else {
286                                         logger(mesh, MESHLINK_WARNING, "Could not resolve node %s to a known address family type.\n", node->name);
287                                 }
288                         } else {
289                                 logger(mesh, MESHLINK_WARNING, "Node %s is not part of the mesh network.\n", node_name);
290                         }
291
292                         pthread_mutex_unlock(&mesh->mutex);
293                 }
294         }
295
296         catta_s_service_resolver_free(resolver);
297 }
298
299 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) {
300         (void)browser;
301         (void)flags;
302         meshlink_handle_t *mesh = userdata;
303
304         /* Called whenever a new services becomes available on the LAN or is removed from the LAN */
305         switch(event) {
306         case CATTA_BROWSER_FAILURE:
307                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
308                         abort();
309                 }
310
311                 catta_simple_poll_quit(mesh->catta_poll);
312                 pthread_mutex_unlock(&mesh->mutex);
313                 break;
314
315         case CATTA_BROWSER_NEW:
316                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
317                         abort();
318                 }
319
320                 catta_s_service_resolver_new(mesh->catta_server, interface_, protocol, name, type, domain, CATTA_PROTO_UNSPEC, 0, discovery_resolve_callback, mesh);
321                 handle_network_change(mesh, ++mesh->catta_interfaces);
322                 pthread_mutex_unlock(&mesh->mutex);
323                 break;
324
325         case CATTA_BROWSER_REMOVE:
326                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
327                         abort();
328                 }
329
330                 handle_network_change(mesh, --mesh->catta_interfaces);
331                 pthread_mutex_unlock(&mesh->mutex);
332                 break;
333
334         case CATTA_BROWSER_ALL_FOR_NOW:
335         case CATTA_BROWSER_CACHE_EXHAUSTED:
336                 break;
337         }
338 }
339
340 static void discovery_log_cb(CattaLogLevel level, const char *txt) {
341         meshlink_log_level_t mlevel = MESHLINK_CRITICAL;
342
343         switch(level) {
344         case CATTA_LOG_ERROR:
345                 mlevel = MESHLINK_ERROR;
346                 break;
347
348         case CATTA_LOG_WARN:
349                 mlevel = MESHLINK_WARNING;
350                 break;
351
352         case CATTA_LOG_NOTICE:
353         case CATTA_LOG_INFO:
354                 mlevel = MESHLINK_INFO;
355                 break;
356
357         case CATTA_LOG_DEBUG:
358         default:
359                 mlevel = MESHLINK_DEBUG;
360                 break;
361         }
362
363         logger(NULL, mlevel, "%s\n", txt);
364 }
365
366 static void *discovery_loop(void *userdata) {
367         bool status = false;
368         meshlink_handle_t *mesh = userdata;
369         assert(mesh);
370
371         if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
372                 abort();
373         }
374
375         // handle catta logs
376         catta_set_log_function(discovery_log_cb);
377
378         // create service type string
379         char appname[strlen(mesh->appname) + 2];
380         strcpy(appname, mesh->appname);
381
382         for(char *p = appname; *p; p++) {
383                 if(!isalnum(*p) && *p != '_' && *p != '-') {
384                         *p = '_';
385                 }
386         }
387
388         if(!appname[1]) {
389                 appname[1] = '_';
390                 appname[2] = '\0';
391         }
392
393         size_t servicetype_strlen = sizeof(MESHLINK_MDNS_SERVICE_TYPE) + strlen(appname) + 1;
394         mesh->catta_servicetype = malloc(servicetype_strlen);
395
396         if(mesh->catta_servicetype == NULL) {
397                 logger(mesh, MESHLINK_ERROR, "Failed to allocate memory for service type string.\n");
398                 goto fail;
399         }
400
401         snprintf(mesh->catta_servicetype, servicetype_strlen, MESHLINK_MDNS_SERVICE_TYPE, appname);
402
403         // Allocate discovery loop object
404         if(!(mesh->catta_poll = catta_simple_poll_new())) {
405                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery poll object.\n");
406                 goto fail;
407         }
408
409         // generate some unique host name (we actually do not care about it)
410         char hostname[17];
411         generate_rand_string(mesh, hostname, sizeof(hostname));
412
413         // Let's set the host name for this server.
414         CattaServerConfig config;
415         catta_server_config_init(&config);
416         config.host_name = catta_strdup(hostname);
417         config.publish_workstation = 0;
418         config.disallow_other_stacks = 0;
419         config.publish_hinfo = 0;
420         config.publish_addresses = 1;
421         config.publish_no_reverse = 1;
422         config.allow_point_to_point = 1;
423
424         /* Allocate a new server */
425         int error;
426         const CattaPoll *poller = catta_simple_poll_get(mesh->catta_poll);
427
428         if(!poller) {
429                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
430                 goto fail;
431         }
432
433         mesh->catta_server = catta_server_new(poller, &config, discovery_server_callback, mesh, &error);
434
435         /* Free the configuration data */
436         catta_server_config_free(&config);
437
438         /* Check whether creating the server object succeeded */
439         if(!mesh->catta_server) {
440                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
441                 goto fail;
442         }
443
444         // Create the service browser
445         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))) {
446                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery service browser: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
447                 goto fail;
448         }
449
450         status = true;
451
452 fail:
453
454         pthread_cond_broadcast(&mesh->discovery_cond);
455         pthread_mutex_unlock(&mesh->discovery_mutex);
456
457         if(status) {
458                 catta_simple_poll_loop(mesh->catta_poll);
459         }
460
461         if(mesh->catta_browser) {
462                 catta_s_service_browser_free(mesh->catta_browser);
463                 mesh->catta_browser = NULL;
464         }
465
466         if(mesh->catta_group) {
467                 catta_s_entry_group_reset(mesh->catta_group);
468                 catta_s_entry_group_free(mesh->catta_group);
469                 mesh->catta_group = NULL;
470         }
471
472         if(mesh->catta_server) {
473                 catta_server_free(mesh->catta_server);
474                 mesh->catta_server = NULL;
475         }
476
477         if(mesh->catta_poll) {
478                 catta_simple_poll_free(mesh->catta_poll);
479                 mesh->catta_poll = NULL;
480         }
481
482         if(mesh->catta_servicetype) {
483                 free(mesh->catta_servicetype);
484                 mesh->catta_servicetype = NULL;
485         }
486
487         return NULL;
488 }
489
490 #ifdef RTM_NEWADDR
491 static void pfroute_io_handler(event_loop_t *loop, void *data, int flags) {
492         (void)flags;
493         static time_t prev_update;
494         meshlink_handle_t *mesh = data;
495
496         struct {
497                 struct rt_msghdr rtm;
498                 char data[2048];
499         } msg;
500
501         while(true) {
502                 msg.rtm.rtm_version = 0;
503                 ssize_t result = recv(mesh->pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
504
505                 if(result <= 0) {
506                         if(result == 0 || errno == EAGAIN || errno == EINTR) {
507                                 break;
508                         }
509
510                         logger(mesh, MESHLINK_ERROR, "Reading from PFROUTE socket failed: %s\n", strerror(errno));
511                         io_set(loop, &mesh->pfroute_io, 0);
512                 }
513
514                 if(msg.rtm.rtm_version != RTM_VERSION) {
515                         logger(mesh, MESHLINK_ERROR, "Invalid PFROUTE message version\n");
516                         break;
517                 }
518
519                 switch(msg.rtm.rtm_type) {
520                 case RTM_IFINFO:
521                 case RTM_NEWADDR:
522                 case RTM_DELADDR:
523                         if(loop->now.tv_sec > prev_update + 5) {
524                                 prev_update = loop->now.tv_sec;
525                                 handle_network_change(mesh, 1);
526                         }
527
528                         break;
529
530                 default:
531                         break;
532                 }
533         }
534 }
535 #endif
536
537 bool discovery_start(meshlink_handle_t *mesh) {
538         logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
539
540         assert(mesh);
541         assert(!mesh->catta_poll);
542         assert(!mesh->catta_server);
543         assert(!mesh->catta_browser);
544         assert(!mesh->discovery_threadstarted);
545         assert(!mesh->catta_servicetype);
546
547         if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
548                 abort();
549         }
550
551         // Start the discovery thread
552         if(pthread_create(&mesh->discovery_thread, NULL, discovery_loop, mesh) != 0) {
553                 pthread_mutex_unlock(&mesh->discovery_mutex);
554                 logger(mesh, MESHLINK_ERROR, "Could not start discovery thread: %s\n", strerror(errno));
555                 memset(&mesh->discovery_thread, 0, sizeof(mesh)->discovery_thread);
556                 return false;
557         }
558
559         pthread_cond_wait(&mesh->discovery_cond, &mesh->discovery_mutex);
560         pthread_mutex_unlock(&mesh->discovery_mutex);
561
562         mesh->discovery_threadstarted = true;
563
564 #ifdef RTM_NEWADDR
565         int sock = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
566
567         if(sock != -1) {
568                 io_add(&mesh->loop, &mesh->pfroute_io, pfroute_io_handler, mesh, sock, IO_READ);
569         } else {
570                 logger(mesh, MESHLINK_WARNING, "Could not open PF_ROUTE socket: %s", strerror(errno));
571         }
572
573 #endif
574
575         return true;
576 }
577
578 void discovery_stop(meshlink_handle_t *mesh) {
579         logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
580
581         assert(mesh);
582
583 #ifdef RTM_NEWADDR
584
585         if(mesh->pfroute_io.cb) {
586                 close(mesh->pfroute_io.fd);
587                 io_del(&mesh->loop, &mesh->pfroute_io);
588         }
589
590 #endif
591
592         // Shut down
593         if(mesh->catta_poll) {
594                 catta_simple_poll_quit(mesh->catta_poll);
595         }
596
597         // Wait for the discovery thread to finish
598         if(mesh->discovery_threadstarted == true) {
599                 if(pthread_join(mesh->discovery_thread, NULL) != 0) {
600                         abort();
601                 }
602
603                 mesh->discovery_threadstarted = false;
604         }
605
606         mesh->catta_interfaces = 0;
607 }