]> git.meshlink.io Git - meshlink/blob - src/discovery.c
Add meshlink_hint_network_change().
[meshlink] / src / discovery.c
1 /*
2   discovery.c -- local network discovery
3   Copyright (C) 2014-2021 Guus Sliepen <guus@meshlink.io>
4
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.
9
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.
14
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.
18 */
19
20 #define __APPLE_USE_RFC_3542
21 #include "system.h"
22
23 #if defined(__APPLE__)
24 #include <CoreFoundation/CoreFoundation.h>
25 #include <CoreFoundation/CFArray.h>
26 #include <CoreFoundation/CFString.h>
27 #include <SystemConfiguration/SystemConfiguration.h>
28 #include <net/if.h>
29 #include <netinet/in.h>
30 #elif defined(__unix) && !defined(__linux)
31 #include <net/if.h>
32 #include <net/route.h>
33 #include <netinet/in.h>
34 #elif defined(__linux)
35 #include <asm/types.h>
36 #include <net/if.h>
37 #include <linux/if_link.h>
38 #include <linux/netlink.h>
39 #include <linux/rtnetlink.h>
40 #endif
41
42 #include "mdns.h"
43 #include "meshlink_internal.h"
44 #include "event.h"
45 #include "discovery.h"
46 #include "sockaddr.h"
47 #include "logger.h"
48 #include "netutl.h"
49 #include "node.h"
50 #include "connection.h"
51 #include "utils.h"
52 #include "xalloc.h"
53
54 #define MESHLINK_MDNS_SERVICE_TYPE "_%s._tcp"
55 #define MESHLINK_MDNS_NAME_KEY "name"
56 #define MESHLINK_MDNS_FINGERPRINT_KEY "fingerprint"
57
58 #ifndef MSG_NOSIGNAL
59 #define MSG_NOSIGNAL 0
60 #endif
61
62 #ifndef IPV6_ADD_MEMBERSHIP
63 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
64 #endif
65
66 #ifndef IPV6_DROP_MEMBERSHIP
67 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
68 #endif
69
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,
74 };
75
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,
82 };
83
84 typedef struct discovery_address {
85         int index;
86         bool up;
87         sockaddr_t address;
88 } discovery_address_t;
89
90 static int iface_compare(const void *va, const void *vb) {
91         const int *a = va;
92         const int *b = vb;
93         return *a - *b;
94 }
95
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;
99
100         if(a->index != b->index) {
101                 return a->index - b->index;
102         }
103
104         return sockaddrcmp_noport(&a->address, &b->address);
105 }
106
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) {
108 #ifdef IP_PKTINFO
109         struct iovec iov  = {
110                 .iov_base = data,
111                 .iov_len = len,
112         };
113
114         struct in_pktinfo pkti = {
115                 .ipi_ifindex = index,
116                 .ipi_addr = src->in.sin_addr,
117         };
118
119         union {
120                 char buf[CMSG_SPACE(sizeof(pkti))];
121                 struct cmsghdr align;
122         } u;
123
124         struct msghdr msg = {
125                 .msg_name = (struct sockaddr *) &dest->sa,
126                 .msg_namelen = SALEN(dest->sa),
127                 .msg_iov = &iov,
128                 .msg_iovlen = 1,
129                 .msg_control = u.buf,
130                 .msg_controllen = sizeof(u.buf),
131         };
132
133
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));
139
140         // Send the packet
141         ssize_t result = sendmsg(fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
142 #else
143         (void)index;
144         (void)src;
145
146         // Send the packet
147         ssize_t result = sendto(fd, data, len, MSG_DONTWAIT | MSG_NOSIGNAL, &dest->sa, SALEN(dest->sa));
148 #endif
149
150         if(result <= 0) {
151                 logger(mesh, MESHLINK_ERROR, "Error sending multicast packet: %s", strerror(errno));
152         }
153 }
154
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) {
156 #ifdef IPV6_PKTINFO
157         struct iovec iov  = {
158                 .iov_base = data,
159                 .iov_len = len,
160         };
161
162         struct in6_pktinfo pkti = {
163                 .ipi6_ifindex = index,
164                 .ipi6_addr = src->in6.sin6_addr,
165         };
166
167         union {
168                 char buf[CMSG_SPACE(sizeof(pkti))];
169                 struct cmsghdr align;
170         } u;
171
172         memset(&u, 0, sizeof u);
173
174         struct msghdr msg = {
175                 .msg_name = (struct sockaddr *) &dest->sa,
176                 .msg_namelen = SALEN(dest->sa),
177                 .msg_iov = &iov,
178                 .msg_iovlen = 1,
179                 .msg_control = u.buf,
180                 .msg_controllen = CMSG_LEN(sizeof(pkti)),
181         };
182
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));
188
189         // Send the packet
190         ssize_t result = sendmsg(fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
191 #else
192         (void)index;
193         (void)src;
194
195         // Send the packet
196         ssize_t result = sendto(fd, data, len, MSG_DONTWAIT | MSG_NOSIGNAL, &dest->sa, SALEN(dest->sa));
197 #endif
198
199         if(result <= 0) {
200                 logger(mesh, MESHLINK_ERROR, "Error sending multicast packet: %s", strerror(errno));
201         }
202 }
203
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
206         int fd;
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);
213         free(fingerprint);
214
215         switch(addr->address.sa.sa_family) {
216         case AF_INET:
217                 fd = mesh->discovery.sockets[0].fd;
218 #ifdef IP_MULTICAST_IF
219                 {
220                         struct ip_mreqn mreq = {
221                                 .imr_address = addr->address.in.sin_addr,
222                                 .imr_ifindex = addr->index,
223                         };
224
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");
227                                 return;
228                         }
229                 }
230
231 #endif
232
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);
235                 break;
236
237         case AF_INET6:
238                 fd = mesh->discovery.sockets[1].fd;
239 #ifdef IPV6_MULTICAST_IF
240
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");
243                         return;
244                 }
245
246 #endif
247
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);
250                 break;
251
252         default:
253                 break;
254         }
255 }
256
257 static void mdns_io_handler(event_loop_t *loop, void *data, int flags) {
258         (void)flags;
259         meshlink_handle_t *mesh = loop->data;
260         io_t *io = data;
261         uint8_t buf[1024];
262         sockaddr_t sa;
263         socklen_t sl = sizeof(sa);
264
265         ssize_t len = recvfrom(io->fd, buf, sizeof(buf), MSG_DONTWAIT, &sa.sa, &sl);
266
267         if(len == -1) {
268                 if(!sockwouldblock(errno)) {
269                         logger(mesh, MESHLINK_ERROR, "Error reading from mDNS discovery socket: %s", strerror(errno));
270                         io_set(loop, io, 0);
271                 }
272
273                 return;
274         }
275
276         char *name = NULL;
277         uint16_t port = 0;
278         const char *keys[2] = {MESHLINK_MDNS_NAME_KEY, MESHLINK_MDNS_FINGERPRINT_KEY};
279         char *values[2] = {NULL, NULL};
280
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]);
283
284                 if(n) {
285                         if(n != mesh->self) {
286                                 logger(mesh, MESHLINK_INFO, "Node %s discovered on the local network.\n", n->name);
287                         }
288
289                         switch(sa.sa.sa_family) {
290                         case AF_INET:
291                                 sa.in.sin_port = htons(port);
292                                 break;
293
294                         case AF_INET6:
295                                 sa.in6.sin6_port = htons(port);
296                                 break;
297
298                         default:
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;
301                                 break;
302                         }
303
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);
308
309                                 if(n->connection) {
310                                         n->connection->last_ping_time = -3600;
311                                 }
312
313                                 for list_each(outgoing_t, outgoing, mesh->outgoings) {
314                                         if(outgoing->node != n) {
315                                                 continue;
316                                         }
317
318                                         outgoing->timeout = 0;
319
320                                         if(outgoing->ev.cb) {
321                                                 timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
322                                                         0, 0
323                                                 });
324                                         }
325                                 }
326                         }
327                 }
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);
334                 free(fingerprint);
335         }
336
337         free(name);
338
339         for(int i = 0; i < 2; i++) {
340                 free(values[i]);
341         }
342 }
343
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);
346
347         if(p) {
348                 return;
349         }
350
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);
354
355         // Add multicast membership
356         struct ip_mreqn mreq4 = {
357                 .imr_multiaddr = mdns_address_ipv4.in.sin_addr,
358                 .imr_ifindex = index,
359         };
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));
362
363         struct ipv6_mreq mreq6 = {
364                 .ipv6mr_multiaddr = mdns_address_ipv6.in6.sin6_addr,
365                 .ipv6mr_interface = index,
366         };
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));
369
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]);
374                 }
375         }
376
377         handle_network_change(mesh, true);
378 }
379
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);
382
383         if(!p) {
384                 return;
385         }
386
387         // Drop multicast membership
388         struct ip_mreqn mreq4 = {
389                 .imr_multiaddr = mdns_address_ipv4.in.sin_addr,
390                 .imr_ifindex = index,
391         };
392         setsockopt(mesh->discovery.sockets[0].fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq4, sizeof(mreq4));
393
394         struct ipv6_mreq mreq6 = {
395                 .ipv6mr_multiaddr = mdns_address_ipv6.in6.sin6_addr,
396                 .ipv6mr_interface = index,
397         };
398         setsockopt(mesh->discovery.sockets[1].fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6));
399
400         memmove(p, p + 1, (mesh->discovery.ifaces + --mesh->discovery.iface_count - p) * sizeof(*p));
401
402         handle_network_change(mesh, mesh->discovery.iface_count);
403 }
404
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);
407
408         if(p) {
409                 return;
410         }
411
412         bool up = bsearch(&addr->index, mesh->discovery.ifaces, mesh->discovery.iface_count, sizeof(int), iface_compare);
413
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;
417
418         if(up) {
419                 send_mdns_packet(mesh, &mesh->discovery.addresses[mesh->discovery.address_count - 1]);
420         }
421
422         qsort(mesh->discovery.addresses, mesh->discovery.address_count, sizeof(*p), address_compare);
423 }
424
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);
427
428         if(!p) {
429                 return;
430         }
431
432         memmove(p, p + 1, (mesh->discovery.addresses + --mesh->discovery.address_count - p) * sizeof(*p));
433 }
434
435 void scan_ifaddrs(meshlink_handle_t *mesh) {
436 #ifdef HAVE_GETIFADDRS
437         struct ifaddrs *ifa = NULL;
438
439         if(getifaddrs(&ifa) == -1) {
440                 logger(mesh, MESHLINK_ERROR, "Could not get list of interface addresses: %s", strerror(errno));
441                 return;
442         }
443
444         // Check for interfaces being removed
445         for(int i = 0; i < mesh->discovery.iface_count;) {
446                 bool found = false;
447
448                 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
449                         if(!ifap->ifa_name) {
450                                 continue;
451                         }
452
453                         int index = if_nametoindex(ifap->ifa_name);
454
455                         if(mesh->discovery.ifaces[i] == index) {
456                                 found = true;
457                                 break;
458                         }
459                 }
460
461                 if(!found) {
462                         iface_down(mesh, mesh->discovery.ifaces[i]);
463                 } else {
464                         i++;
465                 }
466         }
467
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];
471                 bool found = false;
472
473                 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
474                         if(!ifap->ifa_name || !ifap->ifa_addr) {
475                                 continue;
476                         }
477
478                         int index = if_nametoindex(ifap->ifa_name);
479
480                         if(p->index == index && sockaddrcmp_noport(&p->address, (sockaddr_t *)ifap->ifa_addr) == 0) {
481                                 found = true;
482                                 break;
483                         }
484                 }
485
486                 if(!found) {
487                         (void)addr_del;
488                         memmove(p, p + 1, (mesh->discovery.addresses + --mesh->discovery.address_count - p) * sizeof(*p));
489                 } else {
490                         i++;
491                 }
492         }
493
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) {
497                         continue;
498                 }
499
500                 int index = if_nametoindex(ifap->ifa_name);
501
502                 if(ifap->ifa_flags & IFF_UP && ifap->ifa_flags & IFF_MULTICAST && !(ifap->ifa_flags & IFF_LOOPBACK)) {
503                         iface_up(mesh, index);
504                 } else {
505                         iface_down(mesh, index);
506                 }
507
508                 if(!ifap->ifa_addr) {
509                         continue;
510                 }
511
512                 discovery_address_t addr  = {
513                         .index = index,
514                 };
515
516                 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
517
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);
524                 } else {
525                         addr.address.sa.sa_family = AF_UNKNOWN;
526                 }
527
528                 if(addr.address.sa.sa_family != AF_UNKNOWN) {
529                         addr_add(mesh, &addr);
530                 }
531         }
532
533         freeifaddrs(ifa);
534 #else
535         (void)mesh;
536 #endif
537 }
538
539 #if defined(__linux)
540 static void netlink_getlink(int fd) {
541         static const struct {
542                 struct nlmsghdr nlm;
543                 struct ifinfomsg ifi;
544         } msg = {
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,
548                 .nlm.nlmsg_seq = 1,
549                 .ifi.ifi_family = AF_UNSPEC,
550         };
551         send(fd, &msg, msg.nlm.nlmsg_len, 0);
552 }
553
554 static void netlink_getaddr(int fd) {
555         static const struct {
556                 struct nlmsghdr nlm;
557                 struct ifaddrmsg ifa;
558         } msg = {
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,
562                 .nlm.nlmsg_seq = 2,
563                 .ifa.ifa_family = AF_UNSPEC,
564         };
565         send(fd, &msg, msg.nlm.nlmsg_len, 0);
566 }
567
568 static void netlink_parse_link(meshlink_handle_t *mesh, const struct nlmsghdr *nlm) {
569         const struct ifinfomsg *ifi = (const struct ifinfomsg *)(nlm + 1);
570
571         if(ifi->ifi_flags & IFF_UP && ifi->ifi_flags & IFF_MULTICAST) {
572                 iface_up(mesh, ifi->ifi_index);
573         } else {
574                 iface_down(mesh, ifi->ifi_index);
575         }
576 }
577
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);
582
583         while(len >= sizeof(struct rtattr)) {
584                 const struct rtattr *rta = (const struct rtattr *)ptr;
585
586                 if(rta->rta_len <= 0 || rta->rta_len > len) {
587                         break;
588                 }
589
590                 if(rta->rta_type == IFA_ADDRESS) {
591                         discovery_address_t addr  = {
592                                 .index = ifa->ifa_index,
593                         };
594
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;
604                         } else {
605                                 addr.address.sa.sa_family = AF_UNKNOWN;
606                         }
607
608                         if(addr.address.sa.sa_family != AF_UNKNOWN) {
609                                 if(nlm->nlmsg_type == RTM_NEWADDR) {
610                                         addr_add(mesh, &addr);
611                                 } else {
612                                         addr_del(mesh, &addr);
613                                 }
614                         }
615                 }
616
617                 unsigned short rta_len = (rta->rta_len + 3) & ~3;
618                 ptr += rta_len;
619                 len -= rta_len;
620         }
621 }
622
623 static void netlink_parse(meshlink_handle_t *mesh, const void *data, size_t len) {
624         const uint8_t *ptr = data;
625
626         while(len >= sizeof(struct nlmsghdr)) {
627                 const struct nlmsghdr *nlm = (const struct nlmsghdr *)ptr;
628
629                 if(nlm->nlmsg_len > len) {
630                         break;
631                 }
632
633                 switch(nlm->nlmsg_type) {
634                 case RTM_NEWLINK:
635                 case RTM_DELLINK:
636                         netlink_parse_link(mesh, nlm);
637                         break;
638
639                 case RTM_NEWADDR:
640                 case RTM_DELADDR:
641                         netlink_parse_addr(mesh, nlm);
642                 }
643
644                 ptr += nlm->nlmsg_len;
645                 len -= nlm->nlmsg_len;
646         }
647 }
648
649 static void netlink_io_handler(event_loop_t *loop, void *data, int flags) {
650         (void)flags;
651         (void)data;
652         meshlink_handle_t *mesh = loop->data;
653
654         struct {
655                 struct nlmsghdr nlm;
656                 char data[16384];
657         } msg;
658
659         while(true) {
660                 ssize_t result = recv(mesh->discovery.pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
661
662                 if(result <= 0) {
663                         if(result == 0 || errno == EAGAIN || errno == EINTR) {
664                                 break;
665                         }
666
667                         logger(mesh, MESHLINK_ERROR, "Reading from Netlink socket failed: %s\n", strerror(errno));
668                         io_set(loop, &mesh->discovery.pfroute_io, 0);
669                 }
670
671                 if((size_t)result < sizeof(msg.nlm)) {
672                         logger(mesh, MESHLINK_ERROR, "Invalid Netlink message\n");
673                         break;
674                 }
675
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);
680                         }
681                 } else {
682                         netlink_parse(mesh, &msg, result);
683
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);
687                         }
688                 }
689         }
690 }
691 #elif defined(__APPLE__)
692 static void network_change_callback(SCDynamicStoreRef store, CFArrayRef keys, void *info) {
693         (void)store;
694         (void)keys;
695
696         meshlink_handle_t *mesh = info;
697
698         pthread_mutex_lock(&mesh->mutex);
699
700         logger(mesh, MESHLINK_ERROR, "Network change detected!");
701         scan_ifaddrs(mesh);
702
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);
706         }
707
708         pthread_mutex_unlock(&mesh->mutex);
709 }
710
711 static void *network_change_handler(void *arg) {
712         meshlink_handle_t *mesh = arg;
713
714         mesh->discovery.runloop = CFRunLoopGetCurrent();
715
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;
724
725         if(!store) {
726                 logger(mesh, MESHLINK_ERROR, "Error setting up network change handler: %s\n", SCErrorString(SCError()));
727                 goto exit;
728         }
729
730         if(!interfaces || !ipv4 || !ipv6 || !keys || !patterns) {
731                 logger(mesh, MESHLINK_ERROR, "Error setting up network change handler: %s\n", SCErrorString(SCError()));
732                 goto exit;
733         }
734
735         CFArrayAppendValue(keys, interfaces);
736         CFArrayAppendValue(patterns, ipv4);
737         CFArrayAppendValue(patterns, ipv6);
738
739         if(!SCDynamicStoreSetNotificationKeys(store, keys, patterns)) {
740                 logger(mesh, MESHLINK_ERROR, "Error setting up network change handler: %s\n", SCErrorString(SCError()));
741                 goto exit;
742         }
743
744         runloop_source = SCDynamicStoreCreateRunLoopSource(NULL, store, 0);
745
746         if(!runloop_source) {
747                 logger(mesh, MESHLINK_ERROR, "Error setting up network change handler: %s\n", SCErrorString(SCError()));
748                 goto exit;
749         }
750
751         CFRunLoopAddSource(CFRunLoopGetCurrent(), runloop_source, kCFRunLoopDefaultMode);
752         CFRunLoopRun();
753
754 exit:
755
756         if(runloop_source) {
757                 CFRelease(runloop_source);
758         }
759
760         if(interfaces) {
761                 CFRelease(interfaces);
762         }
763
764         if(ipv4) {
765                 CFRelease(ipv4);
766         }
767
768         if(ipv6) {
769                 CFRelease(ipv6);
770         }
771
772         if(keys) {
773                 CFRelease(keys);
774         }
775
776         if(patterns) {
777                 CFRelease(patterns);
778         }
779
780         if(store) {
781                 CFRelease(store);
782         }
783
784         mesh->discovery.runloop = NULL;
785
786         return NULL;
787
788 }
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;
792
793         if(ifm->ifm_flags & IFF_UP && ifm->ifm_flags & IFF_MULTICAST && !(ifm->ifm_flags & IFF_LOOPBACK)) {
794                 iface_up(mesh, ifm->ifm_index);
795         } else {
796                 iface_down(mesh, ifm->ifm_index);
797         }
798 }
799
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);
803
804         for(unsigned int i = 1; i; i <<= 1) {
805                 if(!(ifam->ifam_addrs & i)) {
806                         continue;
807                 }
808
809                 const sockaddr_t *sa = (const sockaddr_t *)p;
810
811                 if(i == RTA_IFA) {
812                         discovery_address_t addr = {
813                                 .index = ifam->ifam_index,
814                         };
815
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);
822                         } else {
823                                 addr.address.sa.sa_family = AF_UNKNOWN;
824                         }
825
826                         if(addr.address.sa.sa_family != AF_UNKNOWN) {
827                                 if(ifam->ifam_type == RTM_NEWADDR) {
828                                         addr_add(mesh, &addr);
829                                 } else {
830                                         addr_del(mesh, &addr);
831                                 }
832                         }
833
834                         break;
835                 }
836
837                 size_t len = (sa->sa.sa_len + 3) & ~3;
838                 p += len;
839         }
840 }
841
842 static void pfroute_io_handler(event_loop_t *loop, void *data, int flags) {
843         (void)flags;
844         (void)data;
845         meshlink_handle_t *mesh = loop->data;
846
847         struct {
848                 struct rt_msghdr rtm;
849                 char data[2048];
850         } msg;
851
852         while(true) {
853                 msg.rtm.rtm_version = 0;
854                 ssize_t result = recv(mesh->discovery.pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
855
856                 if(result <= 0) {
857                         if(result == 0 || errno == EAGAIN || errno == EINTR) {
858                                 break;
859                         }
860
861                         logger(mesh, MESHLINK_ERROR, "Reading from PFROUTE socket failed: %s\n", strerror(errno));
862                         io_set(loop, &mesh->discovery.pfroute_io, 0);
863                 }
864
865                 if(msg.rtm.rtm_version != RTM_VERSION) {
866                         logger(mesh, MESHLINK_ERROR, "Invalid PFROUTE message version\n");
867                         break;
868                 }
869
870                 switch(msg.rtm.rtm_type) {
871                 case RTM_IFINFO:
872                         pfroute_parse_iface(mesh, &msg.rtm);
873                         break;
874
875                 case RTM_NEWADDR:
876                 case RTM_DELADDR:
877                         pfroute_parse_addr(mesh, &msg.rtm);
878                         break;
879
880                 default:
881                         break;
882                 }
883         }
884 }
885 #endif
886
887 bool discovery_start(meshlink_handle_t *mesh) {
888         logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
889
890         assert(mesh);
891
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;
897
898         int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
899
900         if(fd == -1) {
901                 logger(mesh, MESHLINK_ERROR, "Error creating IPv4 socket: %s", strerror(errno));
902         }
903
904         sockaddr_t sa4 = {
905                 .in.sin_family = AF_INET,
906                 .in.sin_port = ntohs(5353),
907         };
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));
912
913         if(bind(fd, &sa4.sa, SALEN(sa4.sa)) == -1) {
914                 logger(mesh, MESHLINK_ERROR, "Error binding to IPv4 multicast socket: %s", strerror(errno));
915         } else {
916                 io_add(&mesh->loop, &mesh->discovery.sockets[0], mdns_io_handler, &mesh->discovery.sockets[0], fd, IO_READ);
917         }
918
919         sockaddr_t sa6 = {
920                 .in6.sin6_family = AF_INET6,
921                 .in6.sin6_port = ntohs(5353),
922         };
923         fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
924
925         if(fd == -1) {
926                 logger(mesh, MESHLINK_ERROR, "Error creating IPv6 socket: %s", strerror(errno));
927         }
928
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));
935
936         if(bind(fd, &sa6.sa, SALEN(sa6.sa)) == -1) {
937                 logger(mesh, MESHLINK_ERROR, "Error binding to IPv4 multicast socket: %s", strerror(errno));
938         } else {
939                 io_add(&mesh->loop, &mesh->discovery.sockets[1], mdns_io_handler, &mesh->discovery.sockets[1], fd, IO_READ);
940         }
941
942 #if defined(__linux)
943         int sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
944
945         if(sock != -1) {
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;
950
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);
954                 } else {
955                         logger(mesh, MESHLINK_WARNING, "Could not bind AF_NETLINK socket: %s", strerror(errno));
956                         scan_ifaddrs(mesh);
957                 }
958         } else {
959                 logger(mesh, MESHLINK_WARNING, "Could not open AF_NETLINK socket: %s", strerror(errno));
960                 scan_ifaddrs(mesh);
961         }
962
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?
966         scan_ifaddrs(mesh);
967 #elif defined(RTM_NEWADDR)
968         int sock = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
969
970         if(sock != -1) {
971                 io_add(&mesh->loop, &mesh->discovery.pfroute_io, pfroute_io_handler, NULL, sock, IO_READ);
972         } else {
973                 logger(mesh, MESHLINK_WARNING, "Could not open PF_ROUTE socket: %s", strerror(errno));
974         }
975
976         scan_ifaddrs(mesh);
977 #endif
978
979         return true;
980 }
981
982 void discovery_stop(meshlink_handle_t *mesh) {
983         logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
984
985         assert(mesh);
986
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;
993
994 #if defined(__APPLE__)
995
996         if(mesh->discovery.runloop) {
997                 CFRunLoopStop(mesh->discovery.runloop);
998                 pthread_join(mesh->discovery.thread, NULL);
999         }
1000
1001 #endif
1002
1003         if(mesh->discovery.pfroute_io.cb) {
1004                 close(mesh->discovery.pfroute_io.fd);
1005                 io_del(&mesh->loop, &mesh->discovery.pfroute_io);
1006         }
1007
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]);
1012                 }
1013         }
1014 }
1015
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]);
1020                 }
1021         }
1022 }