]> git.meshlink.io Git - meshlink/blob - src/discovery.c
Feature external ip address
[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] = 0xff,
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         time_t last_response_sent;
89 } discovery_address_t;
90
91 static int iface_compare(const void *va, const void *vb) {
92         const int *a = va;
93         const int *b = vb;
94         return *a - *b;
95 }
96
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;
100
101         if(a->index != b->index) {
102                 return a->index - b->index;
103         }
104
105         return sockaddrcmp_noport(&a->address, &b->address);
106 }
107
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,
113         };
114
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");
117                 return;
118         }
119
120 #endif
121
122 #ifdef IP_PKTINFO
123         struct iovec iov  = {
124                 .iov_base = data,
125                 .iov_len = len,
126         };
127
128         struct in_pktinfo pkti = {
129                 .ipi_ifindex = index,
130                 .ipi_addr = src->in.sin_addr,
131         };
132
133         union {
134                 char buf[CMSG_SPACE(sizeof(pkti))];
135                 struct cmsghdr align;
136         } u;
137
138         memset(&u, 0, sizeof(u));
139
140         struct msghdr msg = {
141                 .msg_name = (struct sockaddr *) &dest->sa,
142                 .msg_namelen = SALEN(dest->sa),
143                 .msg_iov = &iov,
144                 .msg_iovlen = 1,
145                 .msg_control = u.buf,
146                 .msg_controllen = sizeof(u.buf),
147         };
148
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));
154
155         // Send the packet
156         ssize_t result = sendmsg(fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
157 #else
158         (void)index;
159         (void)src;
160
161         // Send the packet
162         ssize_t result = sendto(fd, data, len, MSG_DONTWAIT | MSG_NOSIGNAL, &dest->sa, SALEN(dest->sa));
163 #endif
164
165         if(result <= 0) {
166                 logger(mesh, MESHLINK_ERROR, "Error sending multicast packet: %s", strerror(errno));
167         }
168 }
169
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
172
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");
175                 return;
176         }
177
178 #endif
179
180 #ifdef IPV6_PKTINFO
181         struct iovec iov  = {
182                 .iov_base = data,
183                 .iov_len = len,
184         };
185
186         struct in6_pktinfo pkti = {
187                 .ipi6_ifindex = index,
188                 .ipi6_addr = src->in6.sin6_addr,
189         };
190
191         union {
192                 char buf[CMSG_SPACE(sizeof(pkti))];
193                 struct cmsghdr align;
194         } u;
195
196         memset(&u, 0, sizeof u);
197
198         struct msghdr msg = {
199                 .msg_name = (struct sockaddr *) &dest->sa,
200                 .msg_namelen = SALEN(dest->sa),
201                 .msg_iov = &iov,
202                 .msg_iovlen = 1,
203                 .msg_control = u.buf,
204                 .msg_controllen = CMSG_LEN(sizeof(pkti)),
205         };
206
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));
212
213         // Send the packet
214         ssize_t result = sendmsg(fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
215 #else
216         (void)index;
217         (void)src;
218
219         // Send the packet
220         ssize_t result = sendto(fd, data, len, MSG_DONTWAIT | MSG_NOSIGNAL, &dest->sa, SALEN(dest->sa));
221 #endif
222
223         if(result <= 0) {
224                 logger(mesh, MESHLINK_ERROR, "Error sending multicast packet: %s", strerror(errno));
225         }
226 }
227
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
230         uint8_t msg[1024];
231         size_t msg_size;
232
233         if(response) {
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);
238                 free(fingerprint);
239                 addr->last_response_sent = mesh->loop.now.tv_sec;
240         } else {
241                 msg_size = prepare_request(msg, sizeof msg, mesh->appname, "tcp");
242         }
243
244         switch(addr->address.sa.sa_family) {
245         case AF_INET:
246                 send_mdns_packet_ipv4(mesh, mesh->discovery.sockets[0].fd, addr->index, &addr->address, &mdns_address_ipv4, msg, msg_size);
247                 break;
248
249         case AF_INET6:
250                 send_mdns_packet_ipv6(mesh, mesh->discovery.sockets[1].fd, addr->index, &addr->address, &mdns_address_ipv6, msg, msg_size);
251                 break;
252
253         default:
254                 break;
255         }
256 }
257
258 static void mdns_io_handler(event_loop_t *loop, void *data, int flags) {
259         (void)flags;
260         meshlink_handle_t *mesh = loop->data;
261         io_t *io = data;
262         uint8_t buf[1024];
263         sockaddr_t sa;
264         socklen_t sl = sizeof(sa);
265
266 #ifdef IP_PKTINFO
267         struct iovec iov  = {
268                 .iov_base = buf,
269                 .iov_len = sizeof(buf),
270         };
271
272         union {
273                 char buf[1024];
274                 struct cmsghdr align;
275         } u;
276
277         struct msghdr msg = {
278                 .msg_name = &sa,
279                 .msg_namelen = sl,
280                 .msg_iov = &iov,
281                 .msg_iovlen = 1,
282                 .msg_control = u.buf,
283                 .msg_controllen = sizeof(u.buf),
284         };
285
286         ssize_t len = recvmsg(io->fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
287
288         sl = msg.msg_namelen;
289 #else
290         ssize_t len = recvfrom(io->fd, buf, sizeof(buf), MSG_DONTWAIT, &sa.sa, &sl);
291 #endif
292
293         if(len == -1) {
294                 if(!sockwouldblock(errno)) {
295                         logger(mesh, MESHLINK_ERROR, "Error reading from mDNS discovery socket: %s", strerror(errno));
296                         io_set(loop, io, 0);
297                 }
298
299                 return;
300         }
301
302         char *name = NULL;
303         uint16_t port = 0;
304         const char *keys[2] = {MESHLINK_MDNS_NAME_KEY, MESHLINK_MDNS_FINGERPRINT_KEY};
305         char *values[2] = {NULL, NULL};
306
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]);
309
310                 if(n) {
311                         if(n != mesh->self) {
312                                 logger(mesh, MESHLINK_INFO, "Node %s discovered on the local network.\n", n->name);
313                         }
314
315                         switch(sa.sa.sa_family) {
316                         case AF_INET:
317                                 sa.in.sin_port = htons(port);
318                                 break;
319
320                         case AF_INET6:
321                                 sa.in6.sin6_port = htons(port);
322                                 break;
323
324                         default:
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;
327                                 break;
328                         }
329
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);
334
335                                 if(n->connection) {
336                                         n->connection->last_ping_time = -3600;
337                                 }
338
339                                 for list_each(outgoing_t, outgoing, mesh->outgoings) {
340                                         if(outgoing->node != n) {
341                                                 continue;
342                                         }
343
344                                         outgoing->timeout = 0;
345
346                                         if(outgoing->ev.cb) {
347                                                 timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
348                                                         0, 0
349                                                 });
350                                         }
351                                 }
352                         }
353                 }
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);
358
359                 int index = -1;
360                 int family = AF_UNSPEC;
361
362                 for(struct cmsghdr *cmptr = CMSG_FIRSTHDR(&msg); cmptr != NULL; cmptr = CMSG_NXTHDR(&msg, cmptr)) {
363 #ifdef IP_PKTINFO
364
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;
368                                 family = AF_INET;
369                                 break;
370                         } else
371 #endif
372 #ifdef IPV6_PKTINFO
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;
376                                         family = AF_INET6;
377                                         break;
378                                 }
379
380 #endif
381                 }
382
383                 if(index) {
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];
387
388                                 if(p->index == index && p->address.sa.sa_family == family) {
389                                         send_mdns_packet(mesh, p, true);
390                                 }
391                         }
392                 } else {
393                         // Send a unicast response back
394                         sendto(io->fd, buf, size, MSG_DONTWAIT | MSG_NOSIGNAL, &sa.sa, sl);
395                 }
396
397                 free(fingerprint);
398         }
399
400         free(name);
401
402         for(int i = 0; i < 2; i++) {
403                 free(values[i]);
404         }
405 }
406
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);
409
410         if(p) {
411                 return;
412         }
413
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);
417
418         // Add multicast membership
419         struct ip_mreqn mreq4 = {
420                 .imr_multiaddr = mdns_address_ipv4.in.sin_addr,
421                 .imr_ifindex = index,
422         };
423
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));
426
427         struct ipv6_mreq mreq6 = {
428                 .ipv6mr_multiaddr = mdns_address_ipv6.in6.sin6_addr,
429                 .ipv6mr_interface = index,
430         };
431
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));
434
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);
439                 }
440         }
441
442         handle_network_change(mesh, true);
443 }
444
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);
447
448         if(!p) {
449                 return;
450         }
451
452         // Drop multicast membership
453         struct ip_mreqn mreq4 = {
454                 .imr_multiaddr = mdns_address_ipv4.in.sin_addr,
455                 .imr_ifindex = index,
456         };
457         setsockopt(mesh->discovery.sockets[0].fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq4, sizeof(mreq4));
458
459         struct ipv6_mreq mreq6 = {
460                 .ipv6mr_multiaddr = mdns_address_ipv6.in6.sin6_addr,
461                 .ipv6mr_interface = index,
462         };
463         setsockopt(mesh->discovery.sockets[1].fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6));
464
465         memmove(p, p + 1, (mesh->discovery.ifaces + --mesh->discovery.iface_count - p) * sizeof(*p));
466
467         handle_network_change(mesh, mesh->discovery.iface_count);
468 }
469
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);
472
473         if(p) {
474                 return;
475         }
476
477         bool up = bsearch(&addr->index, mesh->discovery.ifaces, mesh->discovery.iface_count, sizeof(int), iface_compare);
478
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;
482
483         if(up) {
484                 send_mdns_packet(mesh, &mesh->discovery.addresses[mesh->discovery.address_count - 1], false);
485         }
486
487         qsort(mesh->discovery.addresses, mesh->discovery.address_count, sizeof(*p), address_compare);
488 }
489
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);
492
493         if(!p) {
494                 return;
495         }
496
497         memmove(p, p + 1, (mesh->discovery.addresses + --mesh->discovery.address_count - p) * sizeof(*p));
498 }
499
500 void scan_ifaddrs(meshlink_handle_t *mesh) {
501 #ifdef HAVE_GETIFADDRS
502         struct ifaddrs *ifa = NULL;
503
504         if(getifaddrs(&ifa) == -1) {
505                 logger(mesh, MESHLINK_ERROR, "Could not get list of interface addresses: %s", strerror(errno));
506                 return;
507         }
508
509         // Check for interfaces being removed
510         for(int i = 0; i < mesh->discovery.iface_count;) {
511                 bool found = false;
512
513                 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
514                         if(!ifap->ifa_name) {
515                                 continue;
516                         }
517
518                         int index = if_nametoindex(ifap->ifa_name);
519
520                         if(mesh->discovery.ifaces[i] == index) {
521                                 found = true;
522                                 break;
523                         }
524                 }
525
526                 if(!found) {
527                         iface_down(mesh, mesh->discovery.ifaces[i]);
528                 } else {
529                         i++;
530                 }
531         }
532
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];
536                 bool found = false;
537
538                 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
539                         if(!ifap->ifa_name || !ifap->ifa_addr) {
540                                 continue;
541                         }
542
543                         int index = if_nametoindex(ifap->ifa_name);
544
545                         if(p->index == index && sockaddrcmp_noport(&p->address, (sockaddr_t *)ifap->ifa_addr) == 0) {
546                                 found = true;
547                                 break;
548                         }
549                 }
550
551                 if(!found) {
552                         (void)addr_del;
553                         memmove(p, p + 1, (mesh->discovery.addresses + --mesh->discovery.address_count - p) * sizeof(*p));
554                 } else {
555                         i++;
556                 }
557         }
558
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) {
562                         continue;
563                 }
564
565                 int index = if_nametoindex(ifap->ifa_name);
566
567                 if(ifap->ifa_flags & IFF_UP && ifap->ifa_flags & IFF_MULTICAST && !(ifap->ifa_flags & IFF_LOOPBACK)) {
568                         iface_up(mesh, index);
569                 } else {
570                         iface_down(mesh, index);
571                 }
572
573                 if(!ifap->ifa_addr) {
574                         continue;
575                 }
576
577                 discovery_address_t addr  = {
578                         .index = index,
579                 };
580
581                 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
582
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);
589                 } else {
590                         addr.address.sa.sa_family = AF_UNKNOWN;
591                 }
592
593                 if(addr.address.sa.sa_family != AF_UNKNOWN) {
594                         addr_add(mesh, &addr);
595                 }
596         }
597
598         freeifaddrs(ifa);
599 #else
600         (void)mesh;
601 #endif
602 }
603
604 #if defined(__linux)
605 static void netlink_getlink(int fd) {
606         static const struct {
607                 struct nlmsghdr nlm;
608                 struct ifinfomsg ifi;
609         } msg = {
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,
613                 .nlm.nlmsg_seq = 1,
614                 .ifi.ifi_family = AF_UNSPEC,
615         };
616         send(fd, &msg, msg.nlm.nlmsg_len, 0);
617 }
618
619 static void netlink_getaddr(int fd) {
620         static const struct {
621                 struct nlmsghdr nlm;
622                 struct ifaddrmsg ifa;
623         } msg = {
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,
627                 .nlm.nlmsg_seq = 2,
628                 .ifa.ifa_family = AF_UNSPEC,
629         };
630         send(fd, &msg, msg.nlm.nlmsg_len, 0);
631 }
632
633 static void netlink_parse_link(meshlink_handle_t *mesh, const struct nlmsghdr *nlm) {
634         const struct ifinfomsg *ifi = (const struct ifinfomsg *)(nlm + 1);
635
636         if(ifi->ifi_flags & IFF_UP && ifi->ifi_flags & IFF_MULTICAST) {
637                 iface_up(mesh, ifi->ifi_index);
638         } else {
639                 iface_down(mesh, ifi->ifi_index);
640         }
641 }
642
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);
647
648         while(len >= sizeof(struct rtattr)) {
649                 const struct rtattr *rta = (const struct rtattr *)ptr;
650
651                 if(rta->rta_len <= 0 || rta->rta_len > len) {
652                         break;
653                 }
654
655                 if(rta->rta_type == IFA_ADDRESS) {
656                         discovery_address_t addr  = {
657                                 .index = ifa->ifa_index,
658                         };
659
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;
669                         } else {
670                                 addr.address.sa.sa_family = AF_UNKNOWN;
671                         }
672
673                         if(addr.address.sa.sa_family != AF_UNKNOWN) {
674                                 if(nlm->nlmsg_type == RTM_NEWADDR) {
675                                         addr_add(mesh, &addr);
676                                 } else {
677                                         addr_del(mesh, &addr);
678                                 }
679                         }
680                 }
681
682                 unsigned short rta_len = (rta->rta_len + 3) & ~3;
683                 ptr += rta_len;
684                 len -= rta_len;
685         }
686 }
687
688 static void netlink_parse(meshlink_handle_t *mesh, const void *data, size_t len) {
689         const uint8_t *ptr = data;
690
691         while(len >= sizeof(struct nlmsghdr)) {
692                 const struct nlmsghdr *nlm = (const struct nlmsghdr *)ptr;
693
694                 if(nlm->nlmsg_len > len) {
695                         break;
696                 }
697
698                 switch(nlm->nlmsg_type) {
699                 case RTM_NEWLINK:
700                 case RTM_DELLINK:
701                         netlink_parse_link(mesh, nlm);
702                         break;
703
704                 case RTM_NEWADDR:
705                 case RTM_DELADDR:
706                         netlink_parse_addr(mesh, nlm);
707                 }
708
709                 ptr += nlm->nlmsg_len;
710                 len -= nlm->nlmsg_len;
711         }
712 }
713
714 static void netlink_io_handler(event_loop_t *loop, void *data, int flags) {
715         (void)flags;
716         (void)data;
717         meshlink_handle_t *mesh = loop->data;
718
719         struct {
720                 struct nlmsghdr nlm;
721                 char data[16384];
722         } msg;
723
724         while(true) {
725                 ssize_t result = recv(mesh->discovery.pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
726
727                 if(result <= 0) {
728                         if(result == 0 || errno == EAGAIN || errno == EINTR) {
729                                 break;
730                         }
731
732                         logger(mesh, MESHLINK_ERROR, "Reading from Netlink socket failed: %s\n", strerror(errno));
733                         io_set(loop, &mesh->discovery.pfroute_io, 0);
734                 }
735
736                 if((size_t)result < sizeof(msg.nlm)) {
737                         logger(mesh, MESHLINK_ERROR, "Invalid Netlink message\n");
738                         break;
739                 }
740
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);
745                         }
746                 } else {
747                         netlink_parse(mesh, &msg, result);
748
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);
752                         }
753                 }
754         }
755 }
756 #elif defined(__APPLE__)
757 static void reachability_change_callback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
758         (void)reachability;
759         (void)flags;
760
761         meshlink_handle_t *mesh = info;
762
763         pthread_mutex_lock(&mesh->mutex);
764
765         scan_ifaddrs(mesh);
766
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);
771         }
772
773         pthread_mutex_unlock(&mesh->mutex);
774 }
775
776 static void *network_change_handler(void *arg) {
777         meshlink_handle_t *mesh = arg;
778
779         mesh->discovery.runloop = CFRunLoopGetCurrent();
780
781         SCNetworkReachabilityRef reach_v4 = SCNetworkReachabilityCreateWithName(NULL, "93.184.216.34");
782         SCNetworkReachabilityRef reach_v6 = SCNetworkReachabilityCreateWithName(NULL, "2606:2800:220:1:248:1893:25c8:1946");
783
784         SCNetworkReachabilityContext context;
785         memset(&context, 0, sizeof(context));
786         context.info = mesh;
787
788         if(reach_v4) {
789                 SCNetworkReachabilitySetCallback(reach_v4, reachability_change_callback, &context);
790                 SCNetworkReachabilityScheduleWithRunLoop(reach_v4, mesh->discovery.runloop, kCFRunLoopDefaultMode);
791         } else {
792                 logger(mesh, MESHLINK_ERROR, "Could not create IPv4 network reachability watcher");
793         }
794
795         if(reach_v6) {
796                 SCNetworkReachabilitySetCallback(reach_v6, reachability_change_callback, &context);
797                 SCNetworkReachabilityScheduleWithRunLoop(reach_v6, mesh->discovery.runloop, kCFRunLoopDefaultMode);
798         } else {
799                 logger(mesh, MESHLINK_ERROR, "Could not create IPv6 network reachability watcher");
800         }
801
802         CFRunLoopRun();
803
804         mesh->discovery.runloop = NULL;
805
806         if(reach_v4) {
807                 SCNetworkReachabilityUnscheduleFromRunLoop(reach_v4, mesh->discovery.runloop, kCFRunLoopDefaultMode);
808                 CFRelease(reach_v4);
809         }
810
811         if(reach_v6) {
812                 SCNetworkReachabilityUnscheduleFromRunLoop(reach_v6, mesh->discovery.runloop, kCFRunLoopDefaultMode);
813                 CFRelease(reach_v6);
814         }
815
816         return NULL;
817 }
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;
821
822         if(ifm->ifm_flags & IFF_UP && ifm->ifm_flags & IFF_MULTICAST && !(ifm->ifm_flags & IFF_LOOPBACK)) {
823                 iface_up(mesh, ifm->ifm_index);
824         } else {
825                 iface_down(mesh, ifm->ifm_index);
826         }
827 }
828
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);
832
833         for(unsigned int i = 1; i; i <<= 1) {
834                 if(!(ifam->ifam_addrs & i)) {
835                         continue;
836                 }
837
838                 const sockaddr_t *sa = (const sockaddr_t *)p;
839
840                 if(i == RTA_IFA) {
841                         discovery_address_t addr = {
842                                 .index = ifam->ifam_index,
843                         };
844
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);
851                         } else {
852                                 addr.address.sa.sa_family = AF_UNKNOWN;
853                         }
854
855                         if(addr.address.sa.sa_family != AF_UNKNOWN) {
856                                 if(ifam->ifam_type == RTM_NEWADDR) {
857                                         addr_add(mesh, &addr);
858                                 } else {
859                                         addr_del(mesh, &addr);
860                                 }
861                         }
862
863                         break;
864                 }
865
866                 size_t len = (sa->sa.sa_len + 3) & ~3;
867                 p += len;
868         }
869 }
870
871 static void pfroute_io_handler(event_loop_t *loop, void *data, int flags) {
872         (void)flags;
873         (void)data;
874         meshlink_handle_t *mesh = loop->data;
875
876         struct {
877                 struct rt_msghdr rtm;
878                 char data[2048];
879         } msg;
880
881         while(true) {
882                 msg.rtm.rtm_version = 0;
883                 ssize_t result = recv(mesh->discovery.pfroute_io.fd, &msg, sizeof(msg), MSG_DONTWAIT);
884
885                 if(result <= 0) {
886                         if(result == 0 || errno == EAGAIN || errno == EINTR) {
887                                 break;
888                         }
889
890                         logger(mesh, MESHLINK_ERROR, "Reading from PFROUTE socket failed: %s\n", strerror(errno));
891                         io_set(loop, &mesh->discovery.pfroute_io, 0);
892                 }
893
894                 if(msg.rtm.rtm_version != RTM_VERSION) {
895                         logger(mesh, MESHLINK_ERROR, "Invalid PFROUTE message version\n");
896                         break;
897                 }
898
899                 switch(msg.rtm.rtm_type) {
900                 case RTM_IFINFO:
901                         pfroute_parse_iface(mesh, &msg.rtm);
902                         break;
903
904                 case RTM_NEWADDR:
905                 case RTM_DELADDR:
906                         pfroute_parse_addr(mesh, &msg.rtm);
907                         break;
908
909                 default:
910                         break;
911                 }
912         }
913 }
914 #endif
915
916 bool discovery_start(meshlink_handle_t *mesh) {
917         logger(mesh, MESHLINK_DEBUG, "discovery_start called\n");
918
919         assert(mesh);
920
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;
926
927         int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
928
929         if(fd == -1) {
930                 logger(mesh, MESHLINK_ERROR, "Error creating IPv4 socket: %s", strerror(errno));
931         } else {
932
933                 sockaddr_t sa4 = {
934                         .in.sin_family = AF_INET,
935                         .in.sin_port = ntohs(5353),
936                 };
937                 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
938 #ifdef SO_REUSEPORT
939                 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
940 #endif
941 #ifdef IP_PKTINFO
942                 setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &one, sizeof(one));
943 #endif
944                 setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &one8, sizeof(one8));
945                 setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl8, sizeof(ttl8));
946
947                 if(bind(fd, &sa4.sa, SALEN(sa4.sa)) == -1) {
948                         logger(mesh, MESHLINK_ERROR, "Error binding to IPv4 multicast socket: %s", strerror(errno));
949                 } else {
950                         io_add(&mesh->loop, &mesh->discovery.sockets[0], mdns_io_handler, &mesh->discovery.sockets[0], fd, IO_READ);
951                 }
952         }
953
954         fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
955
956         if(fd == -1) {
957                 logger(mesh, MESHLINK_ERROR, "Error creating IPv6 socket: %s", strerror(errno));
958         } else {
959                 sockaddr_t sa6 = {
960                         .in6.sin6_family = AF_INET6,
961                         .in6.sin6_port = ntohs(5353),
962                 };
963
964                 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
965 #ifdef SO_REUSEPORT
966                 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
967 #endif
968 #ifdef IPV6_RECVPKTINFO
969                 setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &one, sizeof(one));
970 #endif
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));
975
976                 if(bind(fd, &sa6.sa, SALEN(sa6.sa)) == -1) {
977                         logger(mesh, MESHLINK_ERROR, "Error binding to IPv6 multicast socket: %s", strerror(errno));
978                 } else {
979                         io_add(&mesh->loop, &mesh->discovery.sockets[1], mdns_io_handler, &mesh->discovery.sockets[1], fd, IO_READ);
980                 }
981         }
982
983 #if defined(__linux)
984         int sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
985
986         if(sock != -1) {
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;
991
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);
995                 } else {
996                         logger(mesh, MESHLINK_WARNING, "Could not bind AF_NETLINK socket: %s", strerror(errno));
997                         scan_ifaddrs(mesh);
998                 }
999         } else {
1000                 logger(mesh, MESHLINK_WARNING, "Could not open AF_NETLINK socket: %s", strerror(errno));
1001                 scan_ifaddrs(mesh);
1002         }
1003
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?
1007         scan_ifaddrs(mesh);
1008 #elif defined(RTM_NEWADDR)
1009         int sock = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
1010
1011         if(sock != -1) {
1012                 io_add(&mesh->loop, &mesh->discovery.pfroute_io, pfroute_io_handler, NULL, sock, IO_READ);
1013         } else {
1014                 logger(mesh, MESHLINK_WARNING, "Could not open PF_ROUTE socket: %s", strerror(errno));
1015         }
1016
1017         scan_ifaddrs(mesh);
1018 #endif
1019
1020         return true;
1021 }
1022
1023 void discovery_stop(meshlink_handle_t *mesh) {
1024         logger(mesh, MESHLINK_DEBUG, "discovery_stop called\n");
1025
1026         assert(mesh);
1027
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;
1034
1035 #if defined(__APPLE__)
1036
1037         if(mesh->discovery.runloop) {
1038                 CFRunLoopStop(mesh->discovery.runloop);
1039                 pthread_join(mesh->discovery.thread, NULL);
1040         }
1041
1042 #endif
1043
1044         if(mesh->discovery.pfroute_io.cb) {
1045                 close(mesh->discovery.pfroute_io.fd);
1046                 io_del(&mesh->loop, &mesh->discovery.pfroute_io);
1047         }
1048
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]);
1053                 }
1054         }
1055 }
1056
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);
1061                 }
1062         }
1063 }