]> git.meshlink.io Git - meshlink/blob - src/discovery.c
Parse Netlink NEW/DELLINK and NEW/DELADDR messages.
[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 #elif defined(__linux)
15 #include <asm/types.h>
16 #include <net/if.h>
17 #include <linux/if_link.h>
18 #include <linux/netlink.h>
19 #include <linux/rtnetlink.h>
20 #endif
21
22 #include "meshlink_internal.h"
23 #include "event.h"
24 #include "discovery.h"
25 #include "sockaddr.h"
26 #include "logger.h"
27 #include "node.h"
28 #include "connection.h"
29 #include "xalloc.h"
30
31 #define MESHLINK_MDNS_SERVICE_TYPE "_%s._tcp"
32 #define MESHLINK_MDNS_NAME_KEY "name"
33 #define MESHLINK_MDNS_FINGERPRINT_KEY "fingerprint"
34
35 static void generate_rand_string(meshlink_handle_t *mesh, char *buffer, size_t size) {
36         assert(size);
37
38         for(size_t i = 0; i < (size - 1); ++i) {
39                 buffer[i] = 'a' + prng(mesh, 'z' - 'a' + 1);
40         }
41
42         buffer[size - 1] = '\0';
43 }
44
45 static void discovery_entry_group_callback(CattaServer *server, CattaSEntryGroup *group, CattaEntryGroupState state, void *userdata) {
46         (void)server;
47         (void)group;
48         meshlink_handle_t *mesh = userdata;
49
50         assert(mesh);
51         assert(mesh->catta_server);
52         assert(mesh->catta_poll);
53
54         /* Called whenever the entry group state changes */
55         switch(state) {
56         case CATTA_ENTRY_GROUP_ESTABLISHED:
57                 /* The entry group has been established successfully */
58                 logger(mesh, MESHLINK_DEBUG, "Catta Service successfully established.\n");
59                 break;
60
61         case CATTA_ENTRY_GROUP_COLLISION:
62                 logger(mesh, MESHLINK_WARNING, "Catta Service collision.\n");
63                 // @TODO can we just set a new name and retry?
64                 break;
65
66         case CATTA_ENTRY_GROUP_FAILURE :
67                 /* Some kind of failure happened while we were registering our services */
68                 logger(mesh, MESHLINK_ERROR, "Catta Entry group failure: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
69                 catta_simple_poll_quit(mesh->catta_poll);
70                 break;
71
72         case CATTA_ENTRY_GROUP_UNCOMMITED:
73         case CATTA_ENTRY_GROUP_REGISTERING:
74                 break;
75         }
76 }
77
78
79 static void discovery_create_services(meshlink_handle_t *mesh) {
80         char *fingerprint = NULL;
81         char *txt_name = NULL;
82         char *txt_fingerprint = NULL;
83
84         assert(mesh);
85         assert(mesh->name);
86         assert(mesh->myport);
87         assert(mesh->catta_server);
88         assert(mesh->catta_poll);
89         assert(mesh->catta_servicetype);
90         assert(mesh->self);
91
92         logger(mesh, MESHLINK_DEBUG, "Adding service\n");
93
94         /* Ifthis is the first time we're called, let's create a new entry group */
95         if(!(mesh->catta_group = catta_s_entry_group_new(mesh->catta_server, discovery_entry_group_callback, mesh))) {
96                 logger(mesh, MESHLINK_ERROR, "catta_entry_group_new() failed: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
97                 goto fail;
98         }
99
100         /* Create txt records */
101         fingerprint = meshlink_get_fingerprint(mesh, (meshlink_node_t *)mesh->self);
102         xasprintf(&txt_name, "%s=%s", MESHLINK_MDNS_NAME_KEY, mesh->name);
103         xasprintf(&txt_fingerprint, "%s=%s", MESHLINK_MDNS_FINGERPRINT_KEY, fingerprint);
104
105         /* Add the service */
106         int ret = 0;
107
108         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) {
109                 logger(mesh, MESHLINK_ERROR, "Failed to add service: %s\n", catta_strerror(ret));
110                 goto fail;
111         }
112
113         /* Tell the server to register the service */
114         if((ret = catta_s_entry_group_commit(mesh->catta_group)) < 0) {
115                 logger(mesh, MESHLINK_ERROR, "Failed to commit entry_group: %s\n", catta_strerror(ret));
116                 goto fail;
117         }
118
119         goto done;
120
121 fail:
122         catta_simple_poll_quit(mesh->catta_poll);
123
124 done:
125         free(fingerprint);
126         free(txt_name);
127         free(txt_fingerprint);
128 }
129
130 static void discovery_server_callback(CattaServer *server, CattaServerState state, void *userdata) {
131         (void)server;
132         meshlink_handle_t *mesh = userdata;
133
134         assert(mesh);
135
136         switch(state) {
137         case CATTA_SERVER_RUNNING:
138
139                 /* The serve has startup successfully and registered its host
140                  * name on the network, so it's time to create our services */
141                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
142                         abort();
143                 }
144
145                 if(!mesh->catta_group) {
146                         discovery_create_services(mesh);
147                 }
148
149                 pthread_mutex_unlock(&mesh->mutex);
150
151                 break;
152
153         case CATTA_SERVER_COLLISION: {
154                 /* A host name collision happened. Let's pick a new name for the server */
155                 char hostname[17];
156                 generate_rand_string(mesh, hostname, sizeof(hostname));
157
158                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
159                         abort();
160                 }
161
162                 assert(mesh->catta_server);
163                 assert(mesh->catta_poll);
164
165                 int result = catta_server_set_host_name(mesh->catta_server, hostname);
166
167                 if(result < 0) {
168                         catta_simple_poll_quit(mesh->catta_poll);
169                 }
170
171                 pthread_mutex_unlock(&mesh->mutex);
172         }
173         break;
174
175         case CATTA_SERVER_REGISTERING:
176                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
177                         abort();
178                 }
179
180                 /* Let's drop our registered services. When the server is back
181                  * in CATTA_SERVER_RUNNING state we will register them
182                  * again with the new host name. */
183                 if(mesh->catta_group) {
184                         catta_s_entry_group_reset(mesh->catta_group);
185                         mesh->catta_group = NULL;
186                 }
187
188                 pthread_mutex_unlock(&mesh->mutex);
189
190                 break;
191
192         case CATTA_SERVER_FAILURE:
193                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
194                         abort();
195                 }
196
197                 assert(mesh->catta_server);
198                 assert(mesh->catta_poll);
199
200                 /* Terminate on failure */
201                 catta_simple_poll_quit(mesh->catta_poll);
202
203                 pthread_mutex_unlock(&mesh->mutex);
204                 break;
205
206         case CATTA_SERVER_INVALID:
207                 break;
208         }
209 }
210
211 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) {
212         (void)interface_;
213         (void)protocol;
214         (void)flags;
215         (void)name;
216         (void)type;
217         (void)domain;
218         (void)host_name;
219
220         meshlink_handle_t *mesh = userdata;
221
222         assert(mesh);
223
224         if(event != CATTA_RESOLVER_FOUND) {
225                 catta_s_service_resolver_free(resolver);
226                 return;
227         }
228
229         // retrieve fingerprint
230         CattaStringList *node_name_li = catta_string_list_find(txt, MESHLINK_MDNS_NAME_KEY);
231         CattaStringList *node_fp_li = catta_string_list_find(txt, MESHLINK_MDNS_FINGERPRINT_KEY);
232
233         if(node_name_li && node_fp_li) {
234                 char *node_name = (char *)catta_string_list_get_text(node_name_li) + strlen(MESHLINK_MDNS_NAME_KEY);
235                 char *node_fp = (char *)catta_string_list_get_text(node_fp_li) + strlen(MESHLINK_MDNS_FINGERPRINT_KEY);
236
237                 if(node_name[0] == '=' && node_fp[0] == '=') {
238                         if(pthread_mutex_lock(&mesh->mutex) != 0) {
239                                 abort();
240                         }
241
242                         node_name += 1;
243
244                         meshlink_node_t *node = meshlink_get_node(mesh, node_name);
245
246                         if(node) {
247                                 logger(mesh, MESHLINK_INFO, "Node %s is part of the mesh network.\n", node->name);
248
249                                 sockaddr_t naddress;
250                                 memset(&naddress, 0, sizeof(naddress));
251
252                                 switch(address->proto) {
253                                 case CATTA_PROTO_INET: {
254                                         naddress.in.sin_family = AF_INET;
255                                         naddress.in.sin_port = htons(port);
256                                         naddress.in.sin_addr.s_addr = address->data.ipv4.address;
257                                 }
258                                 break;
259
260                                 case CATTA_PROTO_INET6: {
261                                         naddress.in6.sin6_family = AF_INET6;
262                                         naddress.in6.sin6_port = htons(port);
263                                         memcpy(naddress.in6.sin6_addr.s6_addr, address->data.ipv6.address, sizeof(naddress.in6.sin6_addr.s6_addr));
264                                 }
265                                 break;
266
267                                 default:
268                                         naddress.unknown.family = AF_UNKNOWN;
269                                         break;
270                                 }
271
272                                 if(naddress.unknown.family != AF_UNKNOWN) {
273                                         node_t *n = (node_t *)node;
274                                         connection_t *c = n->connection;
275
276                                         n->catta_address = naddress;
277                                         node_add_recent_address(mesh, n, &naddress);
278
279                                         if(c && c->outgoing && !c->status.active) {
280                                                 c->outgoing->timeout = 0;
281
282                                                 if(c->outgoing->ev.cb) {
283                                                         timeout_set(&mesh->loop, &c->outgoing->ev, &(struct timespec) {
284                                                                 0, 0
285                                                         });
286                                                 }
287
288                                                 c->last_ping_time = -3600;
289                                         }
290
291                                 } else {
292                                         logger(mesh, MESHLINK_WARNING, "Could not resolve node %s to a known address family type.\n", node->name);
293                                 }
294                         } else {
295                                 logger(mesh, MESHLINK_WARNING, "Node %s is not part of the mesh network.\n", node_name);
296                         }
297
298                         pthread_mutex_unlock(&mesh->mutex);
299                 }
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         /* Called whenever a new services becomes available on the LAN or is removed from the LAN */
311         switch(event) {
312         case CATTA_BROWSER_FAILURE:
313                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
314                         abort();
315                 }
316
317                 catta_simple_poll_quit(mesh->catta_poll);
318                 pthread_mutex_unlock(&mesh->mutex);
319                 break;
320
321         case CATTA_BROWSER_NEW:
322                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
323                         abort();
324                 }
325
326                 catta_s_service_resolver_new(mesh->catta_server, interface_, protocol, name, type, domain, CATTA_PROTO_UNSPEC, 0, discovery_resolve_callback, mesh);
327                 handle_network_change(mesh, ++mesh->catta_interfaces);
328                 pthread_mutex_unlock(&mesh->mutex);
329                 break;
330
331         case CATTA_BROWSER_REMOVE:
332                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
333                         abort();
334                 }
335
336                 handle_network_change(mesh, --mesh->catta_interfaces);
337                 pthread_mutex_unlock(&mesh->mutex);
338                 break;
339
340         case CATTA_BROWSER_ALL_FOR_NOW:
341         case CATTA_BROWSER_CACHE_EXHAUSTED:
342                 break;
343         }
344 }
345
346 static void discovery_log_cb(CattaLogLevel level, const char *txt) {
347         meshlink_log_level_t mlevel = MESHLINK_CRITICAL;
348
349         switch(level) {
350         case CATTA_LOG_ERROR:
351                 mlevel = MESHLINK_ERROR;
352                 break;
353
354         case CATTA_LOG_WARN:
355                 mlevel = MESHLINK_WARNING;
356                 break;
357
358         case CATTA_LOG_NOTICE:
359         case CATTA_LOG_INFO:
360                 mlevel = MESHLINK_INFO;
361                 break;
362
363         case CATTA_LOG_DEBUG:
364         default:
365                 mlevel = MESHLINK_DEBUG;
366                 break;
367         }
368
369         logger(NULL, mlevel, "%s\n", txt);
370 }
371
372 static void *discovery_loop(void *userdata) {
373         bool status = false;
374         meshlink_handle_t *mesh = userdata;
375         assert(mesh);
376
377         if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
378                 abort();
379         }
380
381         // handle catta logs
382         catta_set_log_function(discovery_log_cb);
383
384         // create service type string
385         char appname[strlen(mesh->appname) + 2];
386         strcpy(appname, mesh->appname);
387
388         for(char *p = appname; *p; p++) {
389                 if(!isalnum(*p) && *p != '_' && *p != '-') {
390                         *p = '_';
391                 }
392         }
393
394         if(!appname[1]) {
395                 appname[1] = '_';
396                 appname[2] = '\0';
397         }
398
399         size_t servicetype_strlen = sizeof(MESHLINK_MDNS_SERVICE_TYPE) + strlen(appname) + 1;
400         mesh->catta_servicetype = malloc(servicetype_strlen);
401
402         if(mesh->catta_servicetype == NULL) {
403                 logger(mesh, MESHLINK_ERROR, "Failed to allocate memory for service type string.\n");
404                 goto fail;
405         }
406
407         snprintf(mesh->catta_servicetype, servicetype_strlen, MESHLINK_MDNS_SERVICE_TYPE, appname);
408
409         // Allocate discovery loop object
410         if(!(mesh->catta_poll = catta_simple_poll_new())) {
411                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery poll object.\n");
412                 goto fail;
413         }
414
415         // generate some unique host name (we actually do not care about it)
416         char hostname[17];
417         generate_rand_string(mesh, hostname, sizeof(hostname));
418
419         // Let's set the host name for this server.
420         CattaServerConfig config;
421         catta_server_config_init(&config);
422         config.host_name = catta_strdup(hostname);
423         config.publish_workstation = 0;
424         config.disallow_other_stacks = 0;
425         config.publish_hinfo = 0;
426         config.publish_addresses = 1;
427         config.publish_no_reverse = 1;
428         config.allow_point_to_point = 1;
429
430         /* Allocate a new server */
431         int error;
432         const CattaPoll *poller = catta_simple_poll_get(mesh->catta_poll);
433
434         if(!poller) {
435                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
436                 goto fail;
437         }
438
439         mesh->catta_server = catta_server_new(poller, &config, discovery_server_callback, mesh, &error);
440
441         /* Free the configuration data */
442         catta_server_config_free(&config);
443
444         /* Check whether creating the server object succeeded */
445         if(!mesh->catta_server) {
446                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery server: %s\n", catta_strerror(error));
447                 goto fail;
448         }
449
450         // Create the service browser
451         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))) {
452                 logger(mesh, MESHLINK_ERROR, "Failed to create discovery service browser: %s\n", catta_strerror(catta_server_errno(mesh->catta_server)));
453                 goto fail;
454         }
455
456         status = true;
457
458 fail:
459
460         pthread_cond_broadcast(&mesh->discovery_cond);
461         pthread_mutex_unlock(&mesh->discovery_mutex);
462
463         if(status) {
464                 catta_simple_poll_loop(mesh->catta_poll);
465         }
466
467         if(mesh->catta_browser) {
468                 catta_s_service_browser_free(mesh->catta_browser);
469                 mesh->catta_browser = NULL;
470         }
471
472         if(mesh->catta_group) {
473                 catta_s_entry_group_reset(mesh->catta_group);
474                 catta_s_entry_group_free(mesh->catta_group);
475                 mesh->catta_group = NULL;
476         }
477
478         if(mesh->catta_server) {
479                 catta_server_free(mesh->catta_server);
480                 mesh->catta_server = NULL;
481         }
482
483         if(mesh->catta_poll) {
484                 catta_simple_poll_free(mesh->catta_poll);
485                 mesh->catta_poll = NULL;
486         }
487
488         if(mesh->catta_servicetype) {
489                 free(mesh->catta_servicetype);
490                 mesh->catta_servicetype = NULL;
491         }
492
493         return NULL;
494 }
495
496 #if defined(__linux)
497 static void netlink_getlink(int fd) {
498         static const struct {
499                 struct nlmsghdr nlm;
500                 struct ifinfomsg ifi;
501         } msg = {
502                 .nlm.nlmsg_len = NLMSG_LENGTH(sizeof(msg.ifi)),
503                 .nlm.nlmsg_type = RTM_GETLINK,
504                 .nlm.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
505                 .nlm.nlmsg_seq = 1,
506                 .ifi.ifi_family = AF_UNSPEC,
507         };
508         send(fd, &msg, msg.nlm.nlmsg_len, 0);
509 }
510
511 static void netlink_getaddr(int fd) {
512         static const struct {
513                 struct nlmsghdr nlm;
514                 struct ifaddrmsg ifa;
515         } msg = {
516                 .nlm.nlmsg_len = NLMSG_LENGTH(sizeof(msg.ifa)),
517                 .nlm.nlmsg_type = RTM_GETADDR,
518                 .nlm.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
519                 .nlm.nlmsg_seq = 2,
520                 .ifa.ifa_family = AF_UNSPEC,
521         };
522         send(fd, &msg, msg.nlm.nlmsg_len, 0);
523 }
524
525 static void netlink_parse_link(meshlink_handle_t *mesh, const struct nlmsghdr *nlm) {
526         const struct ifinfomsg *ifi = (const struct ifinfomsg *)(nlm + 1);
527
528         if(ifi->ifi_flags & IFF_UP && ifi->ifi_flags & IFF_MULTICAST) {
529                 logger(mesh, MESHLINK_INFO, "iface %d active\n", ifi->ifi_index);
530         } else {
531                 logger(mesh, MESHLINK_INFO, "iface %d inactive\n", ifi->ifi_index);
532         }
533 }
534
535 static void netlink_parse_addr(meshlink_handle_t *mesh, const struct nlmsghdr *nlm) {
536         const struct ifaddrmsg *ifa = (const struct ifaddrmsg *)(nlm + 1);
537         const uint8_t *ptr = (const uint8_t *)(ifa + 1);
538         size_t len = nlm->nlmsg_len - (ptr - (const uint8_t *)nlm);
539
540         while(len >= sizeof(struct rtattr)) {
541                 const struct rtattr *rta = (const struct rtattr *)ptr;
542
543                 if(rta->rta_len <= 0 || rta->rta_len > len) {
544                         break;
545                 }
546
547                 if(rta->rta_type == IFA_ADDRESS) {
548                         char dest[40] = "?";
549
550                         if(rta->rta_len == 8) {
551                                 inet_ntop(AF_INET, ptr + 4, dest, sizeof dest);
552                         } else if(rta->rta_len == 20) {
553                                 inet_ntop(AF_INET6, ptr + 4, dest, sizeof dest);
554                         }
555
556                         logger(mesh, MESHLINK_INFO, "iface %d address %s %s\n", ifa->ifa_index, dest, nlm->nlmsg_type == RTM_NEWADDR ? "new" : "del");
557                 }
558
559                 unsigned short rta_len = (rta->rta_len + 3) & ~3;
560                 ptr += rta_len;
561                 len -= rta_len;
562         }
563 }
564
565 static void netlink_parse(meshlink_handle_t *mesh, const void *data, size_t len) {
566         const uint8_t *ptr = data;
567
568         while(len >= sizeof(struct nlmsghdr)) {
569                 const struct nlmsghdr *nlm = (const struct nlmsghdr *)ptr;
570
571                 if(nlm->nlmsg_len > len) {
572                         break;
573                 }
574
575                 switch(nlm->nlmsg_type) {
576                 case RTM_NEWLINK:
577                 case RTM_DELLINK:
578                         netlink_parse_link(mesh, nlm);
579                         break;
580
581                 case RTM_NEWADDR:
582                 case RTM_DELADDR:
583                         netlink_parse_addr(mesh, nlm);
584                 }
585
586                 ptr += nlm->nlmsg_len;
587                 len -= nlm->nlmsg_len;
588         }
589 }
590
591 static void netlink_io_handler(event_loop_t *loop, void *data, int flags) {
592         (void)flags;
593         static time_t prev_update;
594         meshlink_handle_t *mesh = data;
595
596         struct {
597                 struct nlmsghdr nlm;
598                 char data[16384];
599         } msg;
600
601         while(true) {
602                 ssize_t result = recv(mesh->pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
603
604                 if(result <= 0) {
605                         if(result == 0 || errno == EAGAIN || errno == EINTR) {
606                                 break;
607                         }
608
609                         logger(mesh, MESHLINK_ERROR, "Reading from Netlink socket failed: %s\n", strerror(errno));
610                         io_set(loop, &mesh->pfroute_io, 0);
611                 }
612
613                 if((size_t)result < sizeof(msg.nlm)) {
614                         logger(mesh, MESHLINK_ERROR, "Invalid Netlink message\n");
615                         break;
616                 }
617
618                 if(msg.nlm.nlmsg_type == NLMSG_DONE) {
619                         if(msg.nlm.nlmsg_seq == 1) {
620                                 // We just got the result of GETLINK, now send GETADDR.
621                                 netlink_getaddr(mesh->pfroute_io.fd);
622                         }
623                 } else {
624                         netlink_parse(mesh, &msg, result);
625
626                         if(loop->now.tv_sec > prev_update + 5) {
627                                 prev_update = loop->now.tv_sec;
628                                 handle_network_change(mesh, 1);
629                         }
630                 }
631         }
632 }
633 #elif defined(RTM_NEWADDR)
634 static void pfroute_io_handler(event_loop_t *loop, void *data, int flags) {
635         (void)flags;
636         static time_t prev_update;
637         meshlink_handle_t *mesh = data;
638
639         struct {
640                 struct rt_msghdr rtm;
641                 char data[2048];
642         } msg;
643
644         while(true) {
645                 msg.rtm.rtm_version = 0;
646                 ssize_t result = recv(mesh->pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
647
648                 if(result <= 0) {
649                         if(result == 0 || errno == EAGAIN || errno == EINTR) {
650                                 break;
651                         }
652
653                         logger(mesh, MESHLINK_ERROR, "Reading from PFROUTE socket failed: %s\n", strerror(errno));
654                         io_set(loop, &mesh->pfroute_io, 0);
655                 }
656
657                 if(msg.rtm.rtm_version != RTM_VERSION) {
658                         logger(mesh, MESHLINK_ERROR, "Invalid PFROUTE message version\n");
659                         break;
660                 }
661
662                 switch(msg.rtm.rtm_type) {
663                 case RTM_IFINFO:
664                 case RTM_NEWADDR:
665                 case RTM_DELADDR:
666                         if(loop->now.tv_sec > prev_update + 5) {
667                                 prev_update = loop->now.tv_sec;
668                                 handle_network_change(mesh, 1);
669                         }
670
671                         break;
672
673                 default:
674                         break;
675                 }
676         }
677 }
678 #endif
679
680 bool discovery_start(meshlink_handle_t *mesh) {
681         logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
682
683         assert(mesh);
684         assert(!mesh->catta_poll);
685         assert(!mesh->catta_server);
686         assert(!mesh->catta_browser);
687         assert(!mesh->discovery_threadstarted);
688         assert(!mesh->catta_servicetype);
689
690         if(pthread_mutex_lock(&mesh->discovery_mutex) != 0) {
691                 abort();
692         }
693
694         // Start the discovery thread
695         if(pthread_create(&mesh->discovery_thread, NULL, discovery_loop, mesh) != 0) {
696                 pthread_mutex_unlock(&mesh->discovery_mutex);
697                 logger(mesh, MESHLINK_ERROR, "Could not start discovery thread: %s\n", strerror(errno));
698                 memset(&mesh->discovery_thread, 0, sizeof(mesh)->discovery_thread);
699                 return false;
700         }
701
702         pthread_cond_wait(&mesh->discovery_cond, &mesh->discovery_mutex);
703         pthread_mutex_unlock(&mesh->discovery_mutex);
704
705         mesh->discovery_threadstarted = true;
706
707 #if defined(__linux)
708         int sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
709
710         if(sock != -1) {
711                 struct sockaddr_nl sa;
712                 memset(&sa, 0, sizeof(sa));
713                 sa.nl_family = AF_NETLINK;
714                 sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR;
715
716                 if(bind(sock, (struct sockaddr *)&sa, sizeof(sa)) != -1) {
717                         io_add(&mesh->loop, &mesh->pfroute_io, netlink_io_handler, mesh, sock, IO_READ);
718                         netlink_getlink(sock);
719                 } else {
720                         logger(mesh, MESHLINK_WARNING, "Could not bind AF_NETLINK socket: %s", strerror(errno));
721                 }
722         } else {
723                 logger(mesh, MESHLINK_WARNING, "Could not open AF_NETLINK socket: %s", strerror(errno));
724         }
725
726 #elif defined(RTM_NEWADDR)
727         int sock = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
728
729         if(sock != -1) {
730                 io_add(&mesh->loop, &mesh->pfroute_io, pfroute_io_handler, mesh, sock, IO_READ);
731         } else {
732                 logger(mesh, MESHLINK_WARNING, "Could not open PF_ROUTE socket: %s", strerror(errno));
733         }
734
735 #endif
736
737         return true;
738 }
739
740 void discovery_stop(meshlink_handle_t *mesh) {
741         logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
742
743         assert(mesh);
744
745         if(mesh->pfroute_io.cb) {
746                 close(mesh->pfroute_io.fd);
747                 io_del(&mesh->loop, &mesh->pfroute_io);
748         }
749
750         // Shut down
751         if(mesh->catta_poll) {
752                 catta_simple_poll_quit(mesh->catta_poll);
753         }
754
755         // Wait for the discovery thread to finish
756         if(mesh->discovery_threadstarted == true) {
757                 if(pthread_join(mesh->discovery_thread, NULL) != 0) {
758                         abort();
759                 }
760
761                 mesh->discovery_threadstarted = false;
762         }
763
764         mesh->catta_interfaces = 0;
765 }