2 discovery.c -- local network discovery
3 Copyright (C) 2014-2021 Guus Sliepen <guus@meshlink.io>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #define __APPLE_USE_RFC_3542
23 #if defined(__APPLE__)
24 #include <CoreFoundation/CoreFoundation.h>
25 #include <CoreFoundation/CFArray.h>
26 #include <CoreFoundation/CFString.h>
27 #include <SystemConfiguration/SystemConfiguration.h>
29 #include <netinet/in.h>
30 #elif defined(__unix) && !defined(__linux)
32 #include <net/route.h>
33 #include <netinet/in.h>
34 #elif defined(__linux)
35 #include <asm/types.h>
37 #include <linux/if_link.h>
38 #include <linux/netlink.h>
39 #include <linux/rtnetlink.h>
43 #include "meshlink_internal.h"
45 #include "discovery.h"
50 #include "connection.h"
54 #define MESHLINK_MDNS_SERVICE_TYPE "_%s._tcp"
55 #define MESHLINK_MDNS_NAME_KEY "name"
56 #define MESHLINK_MDNS_FINGERPRINT_KEY "fingerprint"
59 #define MSG_NOSIGNAL 0
62 #ifndef IPV6_ADD_MEMBERSHIP
63 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
66 #ifndef IPV6_DROP_MEMBERSHIP
67 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
70 static const sockaddr_t mdns_address_ipv4 = {
71 .in.sin_family = AF_INET,
72 .in.sin_addr.s_addr = 0xfb0000e0,
73 .in.sin_port = 0xe914,
76 static const sockaddr_t mdns_address_ipv6 = {
77 .in6.sin6_family = AF_INET6,
78 .in6.sin6_addr.s6_addr[0x0] = 0xfd,
79 .in6.sin6_addr.s6_addr[0x1] = 0x02,
80 .in6.sin6_addr.s6_addr[0xf] = 0xfb,
81 .in6.sin6_port = 0xe914,
84 typedef struct discovery_address {
88 } discovery_address_t;
90 static int iface_compare(const void *va, const void *vb) {
96 static int address_compare(const void *va, const void *vb) {
97 const discovery_address_t *a = va;
98 const discovery_address_t *b = vb;
100 if(a->index != b->index) {
101 return a->index - b->index;
104 return sockaddrcmp_noport(&a->address, &b->address);
107 static void send_mdns_packet_ipv4(meshlink_handle_t *mesh, int fd, int index, const sockaddr_t *src, const sockaddr_t *dest, void *data, size_t len) {
114 struct in_pktinfo pkti = {
115 .ipi_ifindex = index,
116 .ipi_addr = src->in.sin_addr,
120 char buf[CMSG_SPACE(sizeof(pkti))];
121 struct cmsghdr align;
124 struct msghdr msg = {
125 .msg_name = (struct sockaddr *) &dest->sa,
126 .msg_namelen = SALEN(dest->sa),
129 .msg_control = u.buf,
130 .msg_controllen = sizeof(u.buf),
134 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
135 cmsg->cmsg_level = IPPROTO_IP;
136 cmsg->cmsg_type = IP_PKTINFO;
137 cmsg->cmsg_len = CMSG_LEN(sizeof(pkti));
138 memcpy(CMSG_DATA(cmsg), &pkti, sizeof(pkti));
141 ssize_t result = sendmsg(fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
147 ssize_t result = sendto(fd, data, len, MSG_DONTWAIT | MSG_NOSIGNAL, &dest->sa, SALEN(dest->sa));
151 logger(mesh, MESHLINK_ERROR, "Error sending multicast packet: %s", strerror(errno));
155 static void send_mdns_packet_ipv6(meshlink_handle_t *mesh, int fd, int index, const sockaddr_t *src, const sockaddr_t *dest, void *data, size_t len) {
162 struct in6_pktinfo pkti = {
163 .ipi6_ifindex = index,
164 .ipi6_addr = src->in6.sin6_addr,
168 char buf[CMSG_SPACE(sizeof(pkti))];
169 struct cmsghdr align;
172 memset(&u, 0, sizeof u);
174 struct msghdr msg = {
175 .msg_name = (struct sockaddr *) &dest->sa,
176 .msg_namelen = SALEN(dest->sa),
179 .msg_control = u.buf,
180 .msg_controllen = CMSG_LEN(sizeof(pkti)),
183 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
184 cmsg->cmsg_level = IPPROTO_IPV6;
185 cmsg->cmsg_type = IPV6_PKTINFO;
186 cmsg->cmsg_len = CMSG_LEN(sizeof(pkti));
187 memcpy(CMSG_DATA(cmsg), &pkti, sizeof(pkti));
190 ssize_t result = sendmsg(fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
196 ssize_t result = sendto(fd, data, len, MSG_DONTWAIT | MSG_NOSIGNAL, &dest->sa, SALEN(dest->sa));
200 logger(mesh, MESHLINK_ERROR, "Error sending multicast packet: %s", strerror(errno));
204 static void send_mdns_packet(meshlink_handle_t *mesh, const discovery_address_t *addr) {
205 // Configure the socket to send the packet to the right interface
207 uint8_t request[1024], response[1024];
208 char *fingerprint = meshlink_get_fingerprint(mesh, (meshlink_node_t *)mesh->self);
209 const char *keys[] = {MESHLINK_MDNS_NAME_KEY, MESHLINK_MDNS_FINGERPRINT_KEY};
210 const char *values[] = {mesh->name, fingerprint};
211 size_t request_size = prepare_request(request, sizeof request, mesh->appname, "tcp");
212 size_t response_size = prepare_response(response, sizeof response, fingerprint, mesh->appname, "tcp", atoi(mesh->myport), 2, keys, values);
215 switch(addr->address.sa.sa_family) {
217 fd = mesh->discovery.sockets[0].fd;
218 #ifdef IP_MULTICAST_IF
220 struct ip_mreqn mreq = {
221 .imr_address = addr->address.in.sin_addr,
222 .imr_ifindex = addr->index,
225 if(setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof(mreq)) != 0) {
226 logger(mesh, MESHLINK_ERROR, "Could not set outgoing multicast interface on IPv4 socket");
233 send_mdns_packet_ipv4(mesh, fd, addr->index, &addr->address, &mdns_address_ipv4, request, request_size);
234 send_mdns_packet_ipv4(mesh, fd, addr->index, &addr->address, &mdns_address_ipv4, response, response_size);
238 fd = mesh->discovery.sockets[1].fd;
239 #ifdef IPV6_MULTICAST_IF
241 if(setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &addr->index, sizeof(addr->index)) != 0) {
242 logger(mesh, MESHLINK_ERROR, "Could not set outgoing multicast interface on IPv6 socket");
248 send_mdns_packet_ipv6(mesh, fd, addr->index, &addr->address, &mdns_address_ipv6, request, request_size);
249 send_mdns_packet_ipv6(mesh, fd, addr->index, &addr->address, &mdns_address_ipv6, response, response_size);
257 static void mdns_io_handler(event_loop_t *loop, void *data, int flags) {
259 meshlink_handle_t *mesh = loop->data;
263 socklen_t sl = sizeof(sa);
265 ssize_t len = recvfrom(io->fd, buf, sizeof(buf), MSG_DONTWAIT, &sa.sa, &sl);
268 if(!sockwouldblock(errno)) {
269 logger(mesh, MESHLINK_ERROR, "Error reading from mDNS discovery socket: %s", strerror(errno));
278 const char *keys[2] = {MESHLINK_MDNS_NAME_KEY, MESHLINK_MDNS_FINGERPRINT_KEY};
279 char *values[2] = {NULL, NULL};
281 if(parse_response(buf, len, &name, mesh->appname, "tcp", &port, 2, keys, values)) {
282 node_t *n = (node_t *)meshlink_get_node(mesh, values[0]);
285 if(n != mesh->self) {
286 logger(mesh, MESHLINK_INFO, "Node %s discovered on the local network.\n", n->name);
289 switch(sa.sa.sa_family) {
291 sa.in.sin_port = htons(port);
295 sa.in6.sin6_port = htons(port);
299 logger(mesh, MESHLINK_WARNING, "Could not resolve node %s to a known address family type.\n", n->name);
300 sa.sa.sa_family = AF_UNKNOWN;
304 if(sa.sa.sa_family != AF_UNKNOWN) {
305 n->catta_address = sa;
306 n->last_connect_try = 0;
307 node_add_recent_address(mesh, n, &sa);
310 n->connection->last_ping_time = -3600;
313 for list_each(outgoing_t, outgoing, mesh->outgoings) {
314 if(outgoing->node != n) {
318 outgoing->timeout = 0;
320 if(outgoing->ev.cb) {
321 timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
328 } else if(parse_request(buf, len, mesh->appname, "tcp")) {
329 // Send a unicast response back
330 char *fingerprint = meshlink_get_fingerprint(mesh, (meshlink_node_t *)mesh->self);
331 const char *response_values[] = {mesh->name, fingerprint};
332 size_t size = prepare_response(buf, sizeof(buf), fingerprint, mesh->appname, "tcp", atoi(mesh->myport), 2, keys, response_values);
333 sendto(io->fd, buf, size, MSG_DONTWAIT | MSG_NOSIGNAL, &sa.sa, sl);
339 for(int i = 0; i < 2; i++) {
344 static void iface_up(meshlink_handle_t *mesh, int index) {
345 int *p = bsearch(&index, mesh->discovery.ifaces, mesh->discovery.iface_count, sizeof(*p), iface_compare);
351 mesh->discovery.ifaces = xrealloc(mesh->discovery.ifaces, ++mesh->discovery.iface_count * sizeof(*p));
352 mesh->discovery.ifaces[mesh->discovery.iface_count - 1] = index;
353 qsort(mesh->discovery.ifaces, mesh->discovery.iface_count, sizeof(*p), iface_compare);
355 // Add multicast membership
356 struct ip_mreqn mreq4 = {
357 .imr_multiaddr = mdns_address_ipv4.in.sin_addr,
358 .imr_ifindex = index,
360 setsockopt(mesh->discovery.sockets[0].fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq4, sizeof(mreq4));
361 setsockopt(mesh->discovery.sockets[0].fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq4, sizeof(mreq4));
363 struct ipv6_mreq mreq6 = {
364 .ipv6mr_multiaddr = mdns_address_ipv6.in6.sin6_addr,
365 .ipv6mr_interface = index,
367 setsockopt(mesh->discovery.sockets[1].fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6));
368 setsockopt(mesh->discovery.sockets[1].fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6));
370 // Send an announcement for all addresses associated with this interface
371 for(int i = 0; i < mesh->discovery.address_count; i++) {
372 if(mesh->discovery.addresses[i].index == index) {
373 send_mdns_packet(mesh, &mesh->discovery.addresses[i]);
377 handle_network_change(mesh, true);
380 static void iface_down(meshlink_handle_t *mesh, int index) {
381 int *p = bsearch(&index, mesh->discovery.ifaces, mesh->discovery.iface_count, sizeof(*p), iface_compare);
387 // Drop multicast membership
388 struct ip_mreqn mreq4 = {
389 .imr_multiaddr = mdns_address_ipv4.in.sin_addr,
390 .imr_ifindex = index,
392 setsockopt(mesh->discovery.sockets[0].fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq4, sizeof(mreq4));
394 struct ipv6_mreq mreq6 = {
395 .ipv6mr_multiaddr = mdns_address_ipv6.in6.sin6_addr,
396 .ipv6mr_interface = index,
398 setsockopt(mesh->discovery.sockets[1].fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6));
400 memmove(p, p + 1, (mesh->discovery.ifaces + --mesh->discovery.iface_count - p) * sizeof(*p));
402 handle_network_change(mesh, mesh->discovery.iface_count);
405 static void addr_add(meshlink_handle_t *mesh, const discovery_address_t *addr) {
406 discovery_address_t *p = bsearch(addr, mesh->discovery.addresses, mesh->discovery.address_count, sizeof(*p), address_compare);
412 bool up = bsearch(&addr->index, mesh->discovery.ifaces, mesh->discovery.iface_count, sizeof(int), iface_compare);
414 mesh->discovery.addresses = xrealloc(mesh->discovery.addresses, ++mesh->discovery.address_count * sizeof(*p));
415 mesh->discovery.addresses[mesh->discovery.address_count - 1] = *addr;
416 mesh->discovery.addresses[mesh->discovery.address_count - 1].up = up;
419 send_mdns_packet(mesh, &mesh->discovery.addresses[mesh->discovery.address_count - 1]);
422 qsort(mesh->discovery.addresses, mesh->discovery.address_count, sizeof(*p), address_compare);
425 static void addr_del(meshlink_handle_t *mesh, const discovery_address_t *addr) {
426 discovery_address_t *p = bsearch(addr, mesh->discovery.addresses, mesh->discovery.address_count, sizeof(*p), address_compare);
432 memmove(p, p + 1, (mesh->discovery.addresses + --mesh->discovery.address_count - p) * sizeof(*p));
435 void scan_ifaddrs(meshlink_handle_t *mesh) {
436 #ifdef HAVE_GETIFADDRS
437 struct ifaddrs *ifa = NULL;
439 if(getifaddrs(&ifa) == -1) {
440 logger(mesh, MESHLINK_ERROR, "Could not get list of interface addresses: %s", strerror(errno));
444 // Check for interfaces being removed
445 for(int i = 0; i < mesh->discovery.iface_count;) {
448 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
449 if(!ifap->ifa_name) {
453 int index = if_nametoindex(ifap->ifa_name);
455 if(mesh->discovery.ifaces[i] == index) {
462 iface_down(mesh, mesh->discovery.ifaces[i]);
468 // Check for addresses being removed
469 for(int i = 0; i < mesh->discovery.address_count;) {
470 discovery_address_t *p = &mesh->discovery.addresses[i];
473 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
474 if(!ifap->ifa_name || !ifap->ifa_addr) {
478 int index = if_nametoindex(ifap->ifa_name);
480 if(p->index == index && sockaddrcmp_noport(&p->address, (sockaddr_t *)ifap->ifa_addr) == 0) {
488 memmove(p, p + 1, (mesh->discovery.addresses + --mesh->discovery.address_count - p) * sizeof(*p));
494 // Check for interfaces state changes and addresses going up
495 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
496 if(!ifap->ifa_name) {
500 int index = if_nametoindex(ifap->ifa_name);
502 if(ifap->ifa_flags & IFF_UP && ifap->ifa_flags & IFF_MULTICAST && !(ifap->ifa_flags & IFF_LOOPBACK)) {
503 iface_up(mesh, index);
505 iface_down(mesh, index);
508 if(!ifap->ifa_addr) {
512 discovery_address_t addr = {
516 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
518 if(sa->sa.sa_family == AF_INET) {
519 memcpy(&addr.address.in, &sa->in, sizeof(sa->in));
520 addr.address.in.sin_port = ntohs(5353);
521 } else if(sa->sa.sa_family == AF_INET6) {
522 memcpy(&addr.address.in6, &sa->in6, sizeof(sa->in6));
523 addr.address.in6.sin6_port = ntohs(5353);
525 addr.address.sa.sa_family = AF_UNKNOWN;
528 if(addr.address.sa.sa_family != AF_UNKNOWN) {
529 addr_add(mesh, &addr);
540 static void netlink_getlink(int fd) {
541 static const struct {
543 struct ifinfomsg ifi;
545 .nlm.nlmsg_len = NLMSG_LENGTH(sizeof(msg.ifi)),
546 .nlm.nlmsg_type = RTM_GETLINK,
547 .nlm.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
549 .ifi.ifi_family = AF_UNSPEC,
551 send(fd, &msg, msg.nlm.nlmsg_len, 0);
554 static void netlink_getaddr(int fd) {
555 static const struct {
557 struct ifaddrmsg ifa;
559 .nlm.nlmsg_len = NLMSG_LENGTH(sizeof(msg.ifa)),
560 .nlm.nlmsg_type = RTM_GETADDR,
561 .nlm.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
563 .ifa.ifa_family = AF_UNSPEC,
565 send(fd, &msg, msg.nlm.nlmsg_len, 0);
568 static void netlink_parse_link(meshlink_handle_t *mesh, const struct nlmsghdr *nlm) {
569 const struct ifinfomsg *ifi = (const struct ifinfomsg *)(nlm + 1);
571 if(ifi->ifi_flags & IFF_UP && ifi->ifi_flags & IFF_MULTICAST) {
572 iface_up(mesh, ifi->ifi_index);
574 iface_down(mesh, ifi->ifi_index);
578 static void netlink_parse_addr(meshlink_handle_t *mesh, const struct nlmsghdr *nlm) {
579 const struct ifaddrmsg *ifa = (const struct ifaddrmsg *)(nlm + 1);
580 const uint8_t *ptr = (const uint8_t *)(ifa + 1);
581 size_t len = nlm->nlmsg_len - (ptr - (const uint8_t *)nlm);
583 while(len >= sizeof(struct rtattr)) {
584 const struct rtattr *rta = (const struct rtattr *)ptr;
586 if(rta->rta_len <= 0 || rta->rta_len > len) {
590 if(rta->rta_type == IFA_ADDRESS) {
591 discovery_address_t addr = {
592 .index = ifa->ifa_index,
595 if(rta->rta_len == 8) {
596 addr.address.sa.sa_family = AF_INET;
597 memcpy(&addr.address.in.sin_addr, ptr + 4, 4);
598 addr.address.in.sin_port = ntohs(5353);
599 } else if(rta->rta_len == 20) {
600 addr.address.sa.sa_family = AF_INET6;
601 memcpy(&addr.address.in6.sin6_addr, ptr + 4, 16);
602 addr.address.in6.sin6_port = ntohs(5353);
603 addr.address.in6.sin6_scope_id = ifa->ifa_index;
605 addr.address.sa.sa_family = AF_UNKNOWN;
608 if(addr.address.sa.sa_family != AF_UNKNOWN) {
609 if(nlm->nlmsg_type == RTM_NEWADDR) {
610 addr_add(mesh, &addr);
612 addr_del(mesh, &addr);
617 unsigned short rta_len = (rta->rta_len + 3) & ~3;
623 static void netlink_parse(meshlink_handle_t *mesh, const void *data, size_t len) {
624 const uint8_t *ptr = data;
626 while(len >= sizeof(struct nlmsghdr)) {
627 const struct nlmsghdr *nlm = (const struct nlmsghdr *)ptr;
629 if(nlm->nlmsg_len > len) {
633 switch(nlm->nlmsg_type) {
636 netlink_parse_link(mesh, nlm);
641 netlink_parse_addr(mesh, nlm);
644 ptr += nlm->nlmsg_len;
645 len -= nlm->nlmsg_len;
649 static void netlink_io_handler(event_loop_t *loop, void *data, int flags) {
652 meshlink_handle_t *mesh = loop->data;
660 ssize_t result = recv(mesh->discovery.pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
663 if(result == 0 || errno == EAGAIN || errno == EINTR) {
667 logger(mesh, MESHLINK_ERROR, "Reading from Netlink socket failed: %s\n", strerror(errno));
668 io_set(loop, &mesh->discovery.pfroute_io, 0);
671 if((size_t)result < sizeof(msg.nlm)) {
672 logger(mesh, MESHLINK_ERROR, "Invalid Netlink message\n");
676 if(msg.nlm.nlmsg_type == NLMSG_DONE) {
677 if(msg.nlm.nlmsg_seq == 1) {
678 // We just got the result of GETLINK, now send GETADDR.
679 netlink_getaddr(mesh->discovery.pfroute_io.fd);
682 netlink_parse(mesh, &msg, result);
684 if(loop->now.tv_sec > mesh->discovery.last_update + 5) {
685 mesh->discovery.last_update = loop->now.tv_sec;
686 handle_network_change(mesh, 1);
691 #elif defined(__APPLE__)
692 static void network_change_callback(SCDynamicStoreRef store, CFArrayRef keys, void *info) {
696 meshlink_handle_t *mesh = info;
698 pthread_mutex_lock(&mesh->mutex);
700 logger(mesh, MESHLINK_ERROR, "Network change detected!");
703 if(mesh->loop.now.tv_sec > mesh->discovery.last_update + 5) {
704 mesh->discovery.last_update = mesh->loop.now.tv_sec;
705 handle_network_change(mesh, 1);
708 pthread_mutex_unlock(&mesh->mutex);
711 static void *network_change_handler(void *arg) {
712 meshlink_handle_t *mesh = arg;
714 mesh->discovery.runloop = CFRunLoopGetCurrent();
716 SCDynamicStoreContext context = {0, mesh, NULL, NULL, NULL};
717 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("network_change_handler"), network_change_callback, &context);
718 CFStringRef interfaces = SCDynamicStoreKeyCreate(NULL, CFSTR("State:/Network/Interface"), kCFStringEncodingUTF8);
719 CFStringRef ipv4 = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4);
720 CFStringRef ipv6 = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv6);
721 CFMutableArrayRef keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
722 CFMutableArrayRef patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
723 CFRunLoopSourceRef runloop_source = NULL;
726 logger(mesh, MESHLINK_ERROR, "Error setting up network change handler: %s\n", SCErrorString(SCError()));
730 if(!interfaces || !ipv4 || !ipv6 || !keys || !patterns) {
731 logger(mesh, MESHLINK_ERROR, "Error setting up network change handler: %s\n", SCErrorString(SCError()));
735 CFArrayAppendValue(keys, interfaces);
736 CFArrayAppendValue(patterns, ipv4);
737 CFArrayAppendValue(patterns, ipv6);
739 if(!SCDynamicStoreSetNotificationKeys(store, keys, patterns)) {
740 logger(mesh, MESHLINK_ERROR, "Error setting up network change handler: %s\n", SCErrorString(SCError()));
744 runloop_source = SCDynamicStoreCreateRunLoopSource(NULL, store, 0);
746 if(!runloop_source) {
747 logger(mesh, MESHLINK_ERROR, "Error setting up network change handler: %s\n", SCErrorString(SCError()));
751 CFRunLoopAddSource(CFRunLoopGetCurrent(), runloop_source, kCFRunLoopDefaultMode);
757 CFRelease(runloop_source);
761 CFRelease(interfaces);
784 mesh->discovery.runloop = NULL;
789 #elif defined(RTM_NEWADDR)
790 static void pfroute_parse_iface(meshlink_handle_t *mesh, const struct rt_msghdr *rtm) {
791 const struct if_msghdr *ifm = (const struct if_msghdr *)rtm;
793 if(ifm->ifm_flags & IFF_UP && ifm->ifm_flags & IFF_MULTICAST && !(ifm->ifm_flags & IFF_LOOPBACK)) {
794 iface_up(mesh, ifm->ifm_index);
796 iface_down(mesh, ifm->ifm_index);
800 static void pfroute_parse_addr(meshlink_handle_t *mesh, const struct rt_msghdr *rtm) {
801 const struct ifa_msghdr *ifam = (const struct ifa_msghdr *)rtm;
802 const char *p = (const char *)(ifam + 1);
804 for(unsigned int i = 1; i; i <<= 1) {
805 if(!(ifam->ifam_addrs & i)) {
809 const sockaddr_t *sa = (const sockaddr_t *)p;
812 discovery_address_t addr = {
813 .index = ifam->ifam_index,
816 if(sa->sa.sa_family == AF_INET) {
817 addr.address.in = sa->in;
818 addr.address.in.sin_port = ntohs(5353);
819 } else if(sa->sa.sa_family == AF_INET6) {
820 addr.address.in6 = sa->in6;
821 addr.address.in6.sin6_port = ntohs(5353);
823 addr.address.sa.sa_family = AF_UNKNOWN;
826 if(addr.address.sa.sa_family != AF_UNKNOWN) {
827 if(ifam->ifam_type == RTM_NEWADDR) {
828 addr_add(mesh, &addr);
830 addr_del(mesh, &addr);
837 size_t len = (sa->sa.sa_len + 3) & ~3;
842 static void pfroute_io_handler(event_loop_t *loop, void *data, int flags) {
845 meshlink_handle_t *mesh = loop->data;
848 struct rt_msghdr rtm;
853 msg.rtm.rtm_version = 0;
854 ssize_t result = recv(mesh->discovery.pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
857 if(result == 0 || errno == EAGAIN || errno == EINTR) {
861 logger(mesh, MESHLINK_ERROR, "Reading from PFROUTE socket failed: %s\n", strerror(errno));
862 io_set(loop, &mesh->discovery.pfroute_io, 0);
865 if(msg.rtm.rtm_version != RTM_VERSION) {
866 logger(mesh, MESHLINK_ERROR, "Invalid PFROUTE message version\n");
870 switch(msg.rtm.rtm_type) {
872 pfroute_parse_iface(mesh, &msg.rtm);
877 pfroute_parse_addr(mesh, &msg.rtm);
887 bool discovery_start(meshlink_handle_t *mesh) {
888 logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
892 // Set up multicast sockets for mDNS
893 static const int one = 1;
894 static const int ttl = 255;
895 static const uint8_t one8 = 1;
896 static const uint8_t ttl8 = 255;
898 int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
901 logger(mesh, MESHLINK_ERROR, "Error creating IPv4 socket: %s", strerror(errno));
905 .in.sin_family = AF_INET,
906 .in.sin_port = ntohs(5353),
908 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
909 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
910 setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &one8, sizeof(one8));
911 setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl8, sizeof(ttl8));
913 if(bind(fd, &sa4.sa, SALEN(sa4.sa)) == -1) {
914 logger(mesh, MESHLINK_ERROR, "Error binding to IPv4 multicast socket: %s", strerror(errno));
916 io_add(&mesh->loop, &mesh->discovery.sockets[0], mdns_io_handler, &mesh->discovery.sockets[0], fd, IO_READ);
920 .in6.sin6_family = AF_INET6,
921 .in6.sin6_port = ntohs(5353),
923 fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
926 logger(mesh, MESHLINK_ERROR, "Error creating IPv6 socket: %s", strerror(errno));
929 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
930 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
931 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one));
932 setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &one, sizeof(one));
933 setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(ttl));
934 setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl));
936 if(bind(fd, &sa6.sa, SALEN(sa6.sa)) == -1) {
937 logger(mesh, MESHLINK_ERROR, "Error binding to IPv4 multicast socket: %s", strerror(errno));
939 io_add(&mesh->loop, &mesh->discovery.sockets[1], mdns_io_handler, &mesh->discovery.sockets[1], fd, IO_READ);
943 int sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
946 struct sockaddr_nl sa;
947 memset(&sa, 0, sizeof(sa));
948 sa.nl_family = AF_NETLINK;
949 sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR;
951 if(bind(sock, (struct sockaddr *)&sa, sizeof(sa)) != -1) {
952 io_add(&mesh->loop, &mesh->discovery.pfroute_io, netlink_io_handler, NULL, sock, IO_READ);
953 netlink_getlink(sock);
955 logger(mesh, MESHLINK_WARNING, "Could not bind AF_NETLINK socket: %s", strerror(errno));
959 logger(mesh, MESHLINK_WARNING, "Could not open AF_NETLINK socket: %s", strerror(errno));
963 #elif defined(__APPLE__)
964 pthread_create(&mesh->discovery.thread, NULL, network_change_handler, mesh);
965 // TODO: Do we need to wait for the thread to start succesfully?
967 #elif defined(RTM_NEWADDR)
968 int sock = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
971 io_add(&mesh->loop, &mesh->discovery.pfroute_io, pfroute_io_handler, NULL, sock, IO_READ);
973 logger(mesh, MESHLINK_WARNING, "Could not open PF_ROUTE socket: %s", strerror(errno));
982 void discovery_stop(meshlink_handle_t *mesh) {
983 logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
987 free(mesh->discovery.ifaces);
988 free(mesh->discovery.addresses);
989 mesh->discovery.ifaces = NULL;
990 mesh->discovery.addresses = NULL;
991 mesh->discovery.iface_count = 0;
992 mesh->discovery.address_count = 0;
994 #if defined(__APPLE__)
996 if(mesh->discovery.runloop) {
997 CFRunLoopStop(mesh->discovery.runloop);
998 pthread_join(mesh->discovery.thread, NULL);
1003 if(mesh->discovery.pfroute_io.cb) {
1004 close(mesh->discovery.pfroute_io.fd);
1005 io_del(&mesh->loop, &mesh->discovery.pfroute_io);
1008 for(int i = 0; i < 2; i++) {
1009 if(mesh->discovery.sockets[i].cb) {
1010 close(mesh->discovery.sockets[i].fd);
1011 io_del(&mesh->loop, &mesh->discovery.sockets[i]);
1016 void discovery_refresh(meshlink_handle_t *mesh) {
1017 for(int i = 0; i < mesh->discovery.address_count; i++) {
1018 if(mesh->discovery.addresses[i].up) {
1019 send_mdns_packet(mesh, &mesh->discovery.addresses[i]);