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] = 0xff,
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 time_t last_response_sent;
89 } discovery_address_t;
91 static int iface_compare(const void *va, const void *vb) {
97 static int address_compare(const void *va, const void *vb) {
98 const discovery_address_t *a = va;
99 const discovery_address_t *b = vb;
101 if(a->index != b->index) {
102 return a->index - b->index;
105 return sockaddrcmp_noport(&a->address, &b->address);
108 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) {
109 #ifdef IP_MULTICAST_IF
110 struct ip_mreqn mreq = {
111 .imr_address = src->in.sin_addr,
112 .imr_ifindex = index,
115 if(setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof(mreq)) != 0) {
116 logger(mesh, MESHLINK_ERROR, "Could not set outgoing multicast interface on IPv4 socket");
128 struct in_pktinfo pkti = {
129 .ipi_ifindex = index,
130 .ipi_addr = src->in.sin_addr,
134 char buf[CMSG_SPACE(sizeof(pkti))];
135 struct cmsghdr align;
138 memset(&u, 0, sizeof(u));
140 struct msghdr msg = {
141 .msg_name = (struct sockaddr *) &dest->sa,
142 .msg_namelen = SALEN(dest->sa),
145 .msg_control = u.buf,
146 .msg_controllen = sizeof(u.buf),
149 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
150 cmsg->cmsg_level = IPPROTO_IP;
151 cmsg->cmsg_type = IP_PKTINFO;
152 cmsg->cmsg_len = CMSG_LEN(sizeof(pkti));
153 memcpy(CMSG_DATA(cmsg), &pkti, sizeof(pkti));
156 ssize_t result = sendmsg(fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
162 ssize_t result = sendto(fd, data, len, MSG_DONTWAIT | MSG_NOSIGNAL, &dest->sa, SALEN(dest->sa));
166 logger(mesh, MESHLINK_ERROR, "Error sending multicast packet: %s", strerror(errno));
170 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) {
171 #ifdef IPV6_MULTICAST_IF
173 if(setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &index, sizeof(index)) != 0) {
174 logger(mesh, MESHLINK_ERROR, "Could not set outgoing multicast interface on IPv6 socket");
186 struct in6_pktinfo pkti = {
187 .ipi6_ifindex = index,
188 .ipi6_addr = src->in6.sin6_addr,
192 char buf[CMSG_SPACE(sizeof(pkti))];
193 struct cmsghdr align;
196 memset(&u, 0, sizeof u);
198 struct msghdr msg = {
199 .msg_name = (struct sockaddr *) &dest->sa,
200 .msg_namelen = SALEN(dest->sa),
203 .msg_control = u.buf,
204 .msg_controllen = CMSG_LEN(sizeof(pkti)),
207 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
208 cmsg->cmsg_level = IPPROTO_IPV6;
209 cmsg->cmsg_type = IPV6_PKTINFO;
210 cmsg->cmsg_len = CMSG_LEN(sizeof(pkti));
211 memcpy(CMSG_DATA(cmsg), &pkti, sizeof(pkti));
214 ssize_t result = sendmsg(fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
220 ssize_t result = sendto(fd, data, len, MSG_DONTWAIT | MSG_NOSIGNAL, &dest->sa, SALEN(dest->sa));
224 logger(mesh, MESHLINK_ERROR, "Error sending multicast packet: %s", strerror(errno));
228 static void send_mdns_packet(meshlink_handle_t *mesh, discovery_address_t *addr, bool response) {
229 // Configure the socket to send the packet to the right interface
234 char *fingerprint = meshlink_get_fingerprint(mesh, (meshlink_node_t *)mesh->self);
235 static const char *keys[] = {MESHLINK_MDNS_NAME_KEY, MESHLINK_MDNS_FINGERPRINT_KEY};
236 const char *values[] = {mesh->name, fingerprint};
237 msg_size = prepare_response(msg, sizeof msg, fingerprint, mesh->appname, "tcp", atoi(mesh->myport), 2, keys, values);
239 addr->last_response_sent = mesh->loop.now.tv_sec;
241 msg_size = prepare_request(msg, sizeof msg, mesh->appname, "tcp");
244 switch(addr->address.sa.sa_family) {
246 send_mdns_packet_ipv4(mesh, mesh->discovery.sockets[0].fd, addr->index, &addr->address, &mdns_address_ipv4, msg, msg_size);
250 send_mdns_packet_ipv6(mesh, mesh->discovery.sockets[1].fd, addr->index, &addr->address, &mdns_address_ipv6, msg, msg_size);
258 static void mdns_io_handler(event_loop_t *loop, void *data, int flags) {
260 meshlink_handle_t *mesh = loop->data;
264 socklen_t sl = sizeof(sa);
269 .iov_len = sizeof(buf),
274 struct cmsghdr align;
277 struct msghdr msg = {
282 .msg_control = u.buf,
283 .msg_controllen = sizeof(u.buf),
286 ssize_t len = recvmsg(io->fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
288 sl = msg.msg_namelen;
290 ssize_t len = recvfrom(io->fd, buf, sizeof(buf), MSG_DONTWAIT, &sa.sa, &sl);
294 if(!sockwouldblock(errno)) {
295 logger(mesh, MESHLINK_ERROR, "Error reading from mDNS discovery socket: %s", strerror(errno));
304 const char *keys[2] = {MESHLINK_MDNS_NAME_KEY, MESHLINK_MDNS_FINGERPRINT_KEY};
305 char *values[2] = {NULL, NULL};
307 if(parse_response(buf, len, &name, mesh->appname, "tcp", &port, 2, keys, values)) {
308 node_t *n = (node_t *)meshlink_get_node(mesh, values[0]);
311 if(n != mesh->self) {
312 logger(mesh, MESHLINK_INFO, "Node %s discovered on the local network.\n", n->name);
315 switch(sa.sa.sa_family) {
317 sa.in.sin_port = htons(port);
321 sa.in6.sin6_port = htons(port);
325 logger(mesh, MESHLINK_WARNING, "Could not resolve node %s to a known address family type.\n", n->name);
326 sa.sa.sa_family = AF_UNKNOWN;
330 if(sa.sa.sa_family != AF_UNKNOWN) {
331 n->catta_address = sa;
332 n->last_connect_try = 0;
333 node_add_recent_address(mesh, n, &sa);
336 n->connection->last_ping_time = -3600;
339 for list_each(outgoing_t, outgoing, mesh->outgoings) {
340 if(outgoing->node != n) {
344 outgoing->timeout = 0;
346 if(outgoing->ev.cb) {
347 timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
354 } else if(parse_request(buf, len, mesh->appname, "tcp")) {
355 char *fingerprint = meshlink_get_fingerprint(mesh, (meshlink_node_t *)mesh->self);
356 const char *response_values[] = {mesh->name, fingerprint};
357 size_t size = prepare_response(buf, sizeof(buf), fingerprint, mesh->appname, "tcp", atoi(mesh->myport), 2, keys, response_values);
360 int family = AF_UNSPEC;
362 for(struct cmsghdr *cmptr = CMSG_FIRSTHDR(&msg); cmptr != NULL; cmptr = CMSG_NXTHDR(&msg, cmptr)) {
365 if(cmptr->cmsg_level == IPPROTO_IP && cmptr->cmsg_type == IP_PKTINFO) {
366 struct in_pktinfo *pktinfo = (struct in_pktinfo *) CMSG_DATA(cmptr);
367 index = pktinfo->ipi_ifindex;
373 if(cmptr->cmsg_level == IPPROTO_IPV6 && cmptr->cmsg_type == IPV6_PKTINFO) {
374 struct in6_pktinfo *pktinfo = (struct in6_pktinfo *) CMSG_DATA(cmptr);
375 index = pktinfo->ipi6_ifindex;
384 // Send a multicast response back using all addresses matching the interface
385 for(int i = 0; i < mesh->discovery.address_count; i++) {
386 discovery_address_t *p = &mesh->discovery.addresses[i];
388 if(p->index == index && p->address.sa.sa_family == family) {
389 send_mdns_packet(mesh, p, true);
393 // Send a unicast response back
394 sendto(io->fd, buf, size, MSG_DONTWAIT | MSG_NOSIGNAL, &sa.sa, sl);
402 for(int i = 0; i < 2; i++) {
407 static void iface_up(meshlink_handle_t *mesh, int index) {
408 int *p = bsearch(&index, mesh->discovery.ifaces, mesh->discovery.iface_count, sizeof(*p), iface_compare);
414 mesh->discovery.ifaces = xrealloc(mesh->discovery.ifaces, ++mesh->discovery.iface_count * sizeof(*p));
415 mesh->discovery.ifaces[mesh->discovery.iface_count - 1] = index;
416 qsort(mesh->discovery.ifaces, mesh->discovery.iface_count, sizeof(*p), iface_compare);
418 // Add multicast membership
419 struct ip_mreqn mreq4 = {
420 .imr_multiaddr = mdns_address_ipv4.in.sin_addr,
421 .imr_ifindex = index,
424 setsockopt(mesh->discovery.sockets[0].fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq4, sizeof(mreq4));
425 setsockopt(mesh->discovery.sockets[0].fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq4, sizeof(mreq4));
427 struct ipv6_mreq mreq6 = {
428 .ipv6mr_multiaddr = mdns_address_ipv6.in6.sin6_addr,
429 .ipv6mr_interface = index,
432 setsockopt(mesh->discovery.sockets[1].fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6));
433 setsockopt(mesh->discovery.sockets[1].fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6));
435 // Send an announcement for all addresses associated with this interface
436 for(int i = 0; i < mesh->discovery.address_count; i++) {
437 if(mesh->discovery.addresses[i].index == index) {
438 send_mdns_packet(mesh, &mesh->discovery.addresses[i], false);
442 handle_network_change(mesh, true);
445 static void iface_down(meshlink_handle_t *mesh, int index) {
446 int *p = bsearch(&index, mesh->discovery.ifaces, mesh->discovery.iface_count, sizeof(*p), iface_compare);
452 // Drop multicast membership
453 struct ip_mreqn mreq4 = {
454 .imr_multiaddr = mdns_address_ipv4.in.sin_addr,
455 .imr_ifindex = index,
457 setsockopt(mesh->discovery.sockets[0].fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq4, sizeof(mreq4));
459 struct ipv6_mreq mreq6 = {
460 .ipv6mr_multiaddr = mdns_address_ipv6.in6.sin6_addr,
461 .ipv6mr_interface = index,
463 setsockopt(mesh->discovery.sockets[1].fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6));
465 memmove(p, p + 1, (mesh->discovery.ifaces + --mesh->discovery.iface_count - p) * sizeof(*p));
467 handle_network_change(mesh, mesh->discovery.iface_count);
470 static void addr_add(meshlink_handle_t *mesh, const discovery_address_t *addr) {
471 discovery_address_t *p = bsearch(addr, mesh->discovery.addresses, mesh->discovery.address_count, sizeof(*p), address_compare);
477 bool up = bsearch(&addr->index, mesh->discovery.ifaces, mesh->discovery.iface_count, sizeof(int), iface_compare);
479 mesh->discovery.addresses = xrealloc(mesh->discovery.addresses, ++mesh->discovery.address_count * sizeof(*p));
480 mesh->discovery.addresses[mesh->discovery.address_count - 1] = *addr;
481 mesh->discovery.addresses[mesh->discovery.address_count - 1].up = up;
484 send_mdns_packet(mesh, &mesh->discovery.addresses[mesh->discovery.address_count - 1], false);
487 qsort(mesh->discovery.addresses, mesh->discovery.address_count, sizeof(*p), address_compare);
490 static void addr_del(meshlink_handle_t *mesh, const discovery_address_t *addr) {
491 discovery_address_t *p = bsearch(addr, mesh->discovery.addresses, mesh->discovery.address_count, sizeof(*p), address_compare);
497 memmove(p, p + 1, (mesh->discovery.addresses + --mesh->discovery.address_count - p) * sizeof(*p));
500 void scan_ifaddrs(meshlink_handle_t *mesh) {
501 #ifdef HAVE_GETIFADDRS
502 struct ifaddrs *ifa = NULL;
504 if(getifaddrs(&ifa) == -1) {
505 logger(mesh, MESHLINK_ERROR, "Could not get list of interface addresses: %s", strerror(errno));
509 // Check for interfaces being removed
510 for(int i = 0; i < mesh->discovery.iface_count;) {
513 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
514 if(!ifap->ifa_name) {
518 int index = if_nametoindex(ifap->ifa_name);
520 if(mesh->discovery.ifaces[i] == index) {
527 iface_down(mesh, mesh->discovery.ifaces[i]);
533 // Check for addresses being removed
534 for(int i = 0; i < mesh->discovery.address_count;) {
535 discovery_address_t *p = &mesh->discovery.addresses[i];
538 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
539 if(!ifap->ifa_name || !ifap->ifa_addr) {
543 int index = if_nametoindex(ifap->ifa_name);
545 if(p->index == index && sockaddrcmp_noport(&p->address, (sockaddr_t *)ifap->ifa_addr) == 0) {
553 memmove(p, p + 1, (mesh->discovery.addresses + --mesh->discovery.address_count - p) * sizeof(*p));
559 // Check for interfaces state changes and addresses going up
560 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
561 if(!ifap->ifa_name) {
565 int index = if_nametoindex(ifap->ifa_name);
567 if(ifap->ifa_flags & IFF_UP && ifap->ifa_flags & IFF_MULTICAST && !(ifap->ifa_flags & IFF_LOOPBACK)) {
568 iface_up(mesh, index);
570 iface_down(mesh, index);
573 if(!ifap->ifa_addr) {
577 discovery_address_t addr = {
581 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
583 if(sa->sa.sa_family == AF_INET) {
584 memcpy(&addr.address.in, &sa->in, sizeof(sa->in));
585 addr.address.in.sin_port = ntohs(5353);
586 } else if(sa->sa.sa_family == AF_INET6) {
587 memcpy(&addr.address.in6, &sa->in6, sizeof(sa->in6));
588 addr.address.in6.sin6_port = ntohs(5353);
590 addr.address.sa.sa_family = AF_UNKNOWN;
593 if(addr.address.sa.sa_family != AF_UNKNOWN) {
594 addr_add(mesh, &addr);
605 static void netlink_getlink(int fd) {
606 static const struct {
608 struct ifinfomsg ifi;
610 .nlm.nlmsg_len = NLMSG_LENGTH(sizeof(msg.ifi)),
611 .nlm.nlmsg_type = RTM_GETLINK,
612 .nlm.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
614 .ifi.ifi_family = AF_UNSPEC,
616 send(fd, &msg, msg.nlm.nlmsg_len, 0);
619 static void netlink_getaddr(int fd) {
620 static const struct {
622 struct ifaddrmsg ifa;
624 .nlm.nlmsg_len = NLMSG_LENGTH(sizeof(msg.ifa)),
625 .nlm.nlmsg_type = RTM_GETADDR,
626 .nlm.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
628 .ifa.ifa_family = AF_UNSPEC,
630 send(fd, &msg, msg.nlm.nlmsg_len, 0);
633 static void netlink_parse_link(meshlink_handle_t *mesh, const struct nlmsghdr *nlm) {
634 const struct ifinfomsg *ifi = (const struct ifinfomsg *)(nlm + 1);
636 if(ifi->ifi_flags & IFF_UP && ifi->ifi_flags & IFF_MULTICAST) {
637 iface_up(mesh, ifi->ifi_index);
639 iface_down(mesh, ifi->ifi_index);
643 static void netlink_parse_addr(meshlink_handle_t *mesh, const struct nlmsghdr *nlm) {
644 const struct ifaddrmsg *ifa = (const struct ifaddrmsg *)(nlm + 1);
645 const uint8_t *ptr = (const uint8_t *)(ifa + 1);
646 size_t len = nlm->nlmsg_len - (ptr - (const uint8_t *)nlm);
648 while(len >= sizeof(struct rtattr)) {
649 const struct rtattr *rta = (const struct rtattr *)ptr;
651 if(rta->rta_len <= 0 || rta->rta_len > len) {
655 if(rta->rta_type == IFA_ADDRESS) {
656 discovery_address_t addr = {
657 .index = ifa->ifa_index,
660 if(rta->rta_len == 8) {
661 addr.address.sa.sa_family = AF_INET;
662 memcpy(&addr.address.in.sin_addr, ptr + 4, 4);
663 addr.address.in.sin_port = ntohs(5353);
664 } else if(rta->rta_len == 20) {
665 addr.address.sa.sa_family = AF_INET6;
666 memcpy(&addr.address.in6.sin6_addr, ptr + 4, 16);
667 addr.address.in6.sin6_port = ntohs(5353);
668 addr.address.in6.sin6_scope_id = ifa->ifa_index;
670 addr.address.sa.sa_family = AF_UNKNOWN;
673 if(addr.address.sa.sa_family != AF_UNKNOWN) {
674 if(nlm->nlmsg_type == RTM_NEWADDR) {
675 addr_add(mesh, &addr);
677 addr_del(mesh, &addr);
682 unsigned short rta_len = (rta->rta_len + 3) & ~3;
688 static void netlink_parse(meshlink_handle_t *mesh, const void *data, size_t len) {
689 const uint8_t *ptr = data;
691 while(len >= sizeof(struct nlmsghdr)) {
692 const struct nlmsghdr *nlm = (const struct nlmsghdr *)ptr;
694 if(nlm->nlmsg_len > len) {
698 switch(nlm->nlmsg_type) {
701 netlink_parse_link(mesh, nlm);
706 netlink_parse_addr(mesh, nlm);
709 ptr += nlm->nlmsg_len;
710 len -= nlm->nlmsg_len;
714 static void netlink_io_handler(event_loop_t *loop, void *data, int flags) {
717 meshlink_handle_t *mesh = loop->data;
725 ssize_t result = recv(mesh->discovery.pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
728 if(result == 0 || errno == EAGAIN || errno == EINTR) {
732 logger(mesh, MESHLINK_ERROR, "Reading from Netlink socket failed: %s\n", strerror(errno));
733 io_set(loop, &mesh->discovery.pfroute_io, 0);
736 if((size_t)result < sizeof(msg.nlm)) {
737 logger(mesh, MESHLINK_ERROR, "Invalid Netlink message\n");
741 if(msg.nlm.nlmsg_type == NLMSG_DONE) {
742 if(msg.nlm.nlmsg_seq == 1) {
743 // We just got the result of GETLINK, now send GETADDR.
744 netlink_getaddr(mesh->discovery.pfroute_io.fd);
747 netlink_parse(mesh, &msg, result);
749 if(loop->now.tv_sec > mesh->discovery.last_update + 5) {
750 mesh->discovery.last_update = loop->now.tv_sec;
751 handle_network_change(mesh, true);
756 #elif defined(__APPLE__)
757 static void reachability_change_callback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
761 meshlink_handle_t *mesh = info;
763 pthread_mutex_lock(&mesh->mutex);
767 if(mesh->loop.now.tv_sec > mesh->discovery.last_update + 5) {
768 logger(mesh, MESHLINK_INFO, "Network change detected");
769 mesh->discovery.last_update = mesh->loop.now.tv_sec;
770 handle_network_change(mesh, true);
773 pthread_mutex_unlock(&mesh->mutex);
776 static void *network_change_handler(void *arg) {
777 meshlink_handle_t *mesh = arg;
779 mesh->discovery.runloop = CFRunLoopGetCurrent();
781 SCNetworkReachabilityRef reach_v4 = SCNetworkReachabilityCreateWithName(NULL, "93.184.216.34");
782 SCNetworkReachabilityRef reach_v6 = SCNetworkReachabilityCreateWithName(NULL, "2606:2800:220:1:248:1893:25c8:1946");
784 SCNetworkReachabilityContext context;
785 memset(&context, 0, sizeof(context));
789 SCNetworkReachabilitySetCallback(reach_v4, reachability_change_callback, &context);
790 SCNetworkReachabilityScheduleWithRunLoop(reach_v4, mesh->discovery.runloop, kCFRunLoopDefaultMode);
792 logger(mesh, MESHLINK_ERROR, "Could not create IPv4 network reachability watcher");
796 SCNetworkReachabilitySetCallback(reach_v6, reachability_change_callback, &context);
797 SCNetworkReachabilityScheduleWithRunLoop(reach_v6, mesh->discovery.runloop, kCFRunLoopDefaultMode);
799 logger(mesh, MESHLINK_ERROR, "Could not create IPv6 network reachability watcher");
804 mesh->discovery.runloop = NULL;
807 SCNetworkReachabilityUnscheduleFromRunLoop(reach_v4, mesh->discovery.runloop, kCFRunLoopDefaultMode);
812 SCNetworkReachabilityUnscheduleFromRunLoop(reach_v6, mesh->discovery.runloop, kCFRunLoopDefaultMode);
818 #elif defined(RTM_NEWADDR)
819 static void pfroute_parse_iface(meshlink_handle_t *mesh, const struct rt_msghdr *rtm) {
820 const struct if_msghdr *ifm = (const struct if_msghdr *)rtm;
822 if(ifm->ifm_flags & IFF_UP && ifm->ifm_flags & IFF_MULTICAST && !(ifm->ifm_flags & IFF_LOOPBACK)) {
823 iface_up(mesh, ifm->ifm_index);
825 iface_down(mesh, ifm->ifm_index);
829 static void pfroute_parse_addr(meshlink_handle_t *mesh, const struct rt_msghdr *rtm) {
830 const struct ifa_msghdr *ifam = (const struct ifa_msghdr *)rtm;
831 const char *p = (const char *)(ifam + 1);
833 for(unsigned int i = 1; i; i <<= 1) {
834 if(!(ifam->ifam_addrs & i)) {
838 const sockaddr_t *sa = (const sockaddr_t *)p;
841 discovery_address_t addr = {
842 .index = ifam->ifam_index,
845 if(sa->sa.sa_family == AF_INET) {
846 addr.address.in = sa->in;
847 addr.address.in.sin_port = ntohs(5353);
848 } else if(sa->sa.sa_family == AF_INET6) {
849 addr.address.in6 = sa->in6;
850 addr.address.in6.sin6_port = ntohs(5353);
852 addr.address.sa.sa_family = AF_UNKNOWN;
855 if(addr.address.sa.sa_family != AF_UNKNOWN) {
856 if(ifam->ifam_type == RTM_NEWADDR) {
857 addr_add(mesh, &addr);
859 addr_del(mesh, &addr);
866 size_t len = (sa->sa.sa_len + 3) & ~3;
871 static void pfroute_io_handler(event_loop_t *loop, void *data, int flags) {
874 meshlink_handle_t *mesh = loop->data;
877 struct rt_msghdr rtm;
882 msg.rtm.rtm_version = 0;
883 ssize_t result = recv(mesh->discovery.pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
886 if(result == 0 || errno == EAGAIN || errno == EINTR) {
890 logger(mesh, MESHLINK_ERROR, "Reading from PFROUTE socket failed: %s\n", strerror(errno));
891 io_set(loop, &mesh->discovery.pfroute_io, 0);
894 if(msg.rtm.rtm_version != RTM_VERSION) {
895 logger(mesh, MESHLINK_ERROR, "Invalid PFROUTE message version\n");
899 switch(msg.rtm.rtm_type) {
901 pfroute_parse_iface(mesh, &msg.rtm);
906 pfroute_parse_addr(mesh, &msg.rtm);
916 bool discovery_start(meshlink_handle_t *mesh) {
917 logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
921 // Set up multicast sockets for mDNS
922 static const int one = 1;
923 static const int ttl = 255;
924 static const uint8_t one8 = 1;
925 static const uint8_t ttl8 = 255;
927 int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
930 logger(mesh, MESHLINK_ERROR, "Error creating IPv4 socket: %s", strerror(errno));
934 .in.sin_family = AF_INET,
935 .in.sin_port = ntohs(5353),
937 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
939 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
942 setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &one, sizeof(one));
944 setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &one8, sizeof(one8));
945 setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl8, sizeof(ttl8));
947 if(bind(fd, &sa4.sa, SALEN(sa4.sa)) == -1) {
948 logger(mesh, MESHLINK_ERROR, "Error binding to IPv4 multicast socket: %s", strerror(errno));
950 io_add(&mesh->loop, &mesh->discovery.sockets[0], mdns_io_handler, &mesh->discovery.sockets[0], fd, IO_READ);
954 fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
957 logger(mesh, MESHLINK_ERROR, "Error creating IPv6 socket: %s", strerror(errno));
960 .in6.sin6_family = AF_INET6,
961 .in6.sin6_port = ntohs(5353),
964 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
966 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
968 #ifdef IPV6_RECVPKTINFO
969 setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &one, sizeof(one));
971 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one));
972 setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &one, sizeof(one));
973 setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(ttl));
974 setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl));
976 if(bind(fd, &sa6.sa, SALEN(sa6.sa)) == -1) {
977 logger(mesh, MESHLINK_ERROR, "Error binding to IPv6 multicast socket: %s", strerror(errno));
979 io_add(&mesh->loop, &mesh->discovery.sockets[1], mdns_io_handler, &mesh->discovery.sockets[1], fd, IO_READ);
984 int sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
987 struct sockaddr_nl sa;
988 memset(&sa, 0, sizeof(sa));
989 sa.nl_family = AF_NETLINK;
990 sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR;
992 if(bind(sock, (struct sockaddr *)&sa, sizeof(sa)) != -1) {
993 io_add(&mesh->loop, &mesh->discovery.pfroute_io, netlink_io_handler, NULL, sock, IO_READ);
994 netlink_getlink(sock);
996 logger(mesh, MESHLINK_WARNING, "Could not bind AF_NETLINK socket: %s", strerror(errno));
1000 logger(mesh, MESHLINK_WARNING, "Could not open AF_NETLINK socket: %s", strerror(errno));
1004 #elif defined(__APPLE__)
1005 pthread_create(&mesh->discovery.thread, NULL, network_change_handler, mesh);
1006 // TODO: Do we need to wait for the thread to start succesfully?
1008 #elif defined(RTM_NEWADDR)
1009 int sock = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
1012 io_add(&mesh->loop, &mesh->discovery.pfroute_io, pfroute_io_handler, NULL, sock, IO_READ);
1014 logger(mesh, MESHLINK_WARNING, "Could not open PF_ROUTE socket: %s", strerror(errno));
1023 void discovery_stop(meshlink_handle_t *mesh) {
1024 logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
1028 free(mesh->discovery.ifaces);
1029 free(mesh->discovery.addresses);
1030 mesh->discovery.ifaces = NULL;
1031 mesh->discovery.addresses = NULL;
1032 mesh->discovery.iface_count = 0;
1033 mesh->discovery.address_count = 0;
1035 #if defined(__APPLE__)
1037 if(mesh->discovery.runloop) {
1038 CFRunLoopStop(mesh->discovery.runloop);
1039 pthread_join(mesh->discovery.thread, NULL);
1044 if(mesh->discovery.pfroute_io.cb) {
1045 close(mesh->discovery.pfroute_io.fd);
1046 io_del(&mesh->loop, &mesh->discovery.pfroute_io);
1049 for(int i = 0; i < 2; i++) {
1050 if(mesh->discovery.sockets[i].cb) {
1051 close(mesh->discovery.sockets[i].fd);
1052 io_del(&mesh->loop, &mesh->discovery.sockets[i]);
1057 void discovery_refresh(meshlink_handle_t *mesh) {
1058 for(int i = 0; i < mesh->discovery.address_count; i++) {
1059 if(mesh->discovery.addresses[i].up) {
1060 send_mdns_packet(mesh, &mesh->discovery.addresses[i], false);