-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Local Network Traversal - Multicast Discovery #1
Comments
The old networking code is located here: https://github.com/MatrixAI/js-polykey/tree/3340fc7508e46a6021d1bd6d9005c99ea598e205/src-old/network There may be some artifacts worth fetching out. Especially implementation of the local network discovery. |
Just a note, AWS's subnets in the VPC by default doesn't support multicast. And thus no mdns. However this can be enabled by creating a transit gateway: https://docs.aws.amazon.com/vpc/latest/tgw/working-with-multicast.html. Haven't tried it though. Multicast is a way of doing "automatic service discovery" (by bootstrapping off a known location). Alternative ways include using AWS's own service discovery, but that's not portable, and limited to specifically ECS or whatever aws provides there. And the only usage for that is to be able to auto-discover a seed node cluster in AWS like we are doing for testnet and mainnet. Without automatic service discovery, deployment of agents into testnet and mainnet has to occur one by one, where each subsequent agent is deployed like a congaline, and has given knowledge of the other agents. I wonder though... perhaps if I did use the auto-sd, maybe I could pass the SD domain/hostnaem directly as the seed node specification, and rely on our DHT to make use of it. Then we would be using AWS's SD but in a portable manner. For the seed nodes, this can be worked around by using the DNS hostname |
Manual testing in MatrixAI/Polykey#487 (comment) has revealed an urgent need for some kind of "local network traversal". Basically if 2 nodes are on the same subnet/LAN and thus have the same public IP address, hole punching using the relay signalling message will not work. This is because the router may not support hairpinning. And therefore the packets just get dropped. This can happen if 2 nodes are running on the same computer, and are using different ports. And it can also happen if 2 nodes are running on the same subnet, and are using different private IPs and ports. It could also happen in more general way where in larger corporate networks. Or even in larger CGNAT scenarios, where the home router themselves are not given a public IP address. Like imagine buying a bunch of nokia 5G routers for home usage, and now every home in a local area may be part of the same CGNAT IP. This can seriously hamper connectivity! |
Local multicase is necessary for local discovery. This means that a given To deal with this, we have to refactor the NG to be capable of dealing with the inherent ambiguity of node addresses. Changing our NG key path to Tailscale seems to support some sort of local discovery, combined with detections of whether hairpinning works, and whether the immediate router supports PMP or PCP.
Meaning that a multitude of methods can be tried before falling back on some centralised relay. |
For the most immediate use case, I think we can solve the problem of:
With the introduction of multicast discovery and expanding our NG to take that ambiguity and resolving it. |
The fact that signalling does work though means that the signalling node is a common source of coordination. It can help do relaying, but it can also help the 2 nodes try to discover each other on the local networks too. If we aren't afraid of "leaking private data", it's possible to provide private network information to the seed node. If we want to hide that information from the seed node, it's possible to encrypt this data for the other node, and rely on the seed node to relay encrypted information to each other. This kind of leads to zero knowledge protocols too. https://www.theguardian.com/technology/2022/oct/29/privacy-problem-tech-enhancing-data-political-legal (I think these are called privacy enhancing protocols). |
Wanted to mention that look to tailscale for inspiration. They also keep track of all local IP:port bindings, and send that off to the tailscale server which is then distributed to other clients, and so other clients can actually just "attempt" DCs to the local IP:port. This actually sometimes works very well, and avoids any need to use complicated MDNS, multicast, PMP... etc protocols. This is still a signaling system. @amydevs first attempt to prototype the multicast system locally on a single computer, then we between computers on a home router (office router). And then look at the network and node graph modules to see how it can be integrated. You need to have a read of the MDNS and multicast RFCs. There are existing libraries for this, but only use those as a guide. You do not need a library for implementation here. |
What I think I've found so far:
These records are created by sending a DNS Response packet to the well-known mdns address. A quick way to check if the service records have been correctly created is with |
The RFC mentions as a recommendation that all clients of a machine should use a single shared MDNS implementation (bonjour, avahi, etc.). I think we ignore this recommendation as:
|
Does the naming matter? Or we just choose Polykey. |
Our standard port is 1314. Does this need to be fixed or can we do this for any port PK binds to? |
Just wondering do we need to do a host announcement? It seems like this is an OS thing. Can we just expect that it is already done? |
There was a commit that I forgot to push before. I removed the At the same time, if you are binding to ipv4, you get ipv4 type, ipv6 to ipv6 type, and if you use ipv4 mapped ipv6... I forgot what the type should be, but it should be the same as whatever js-quic does. Furthermore each socket object should have This means something like this: |
Releasing 1.1.0 of js-table with the iterator changed to give you Also the table indexes options supports hashing functions. The default hashing function has changed to now support |
Should also create your own special |
The uniqueness of a record in mDNS, (even for shared records) is defined by the record's name, class, type, and data. Hence, MDNSCache needs a way to compoundly index by those 4 fields. The main field that is the problem is |
i've moved and renamed MDNSCache to ResourceRecordCache to a separate folder to better reflect what it actually does. The reason for moving it to a separate folder is so that i can separate the utils, events, and errors for the cache |
What's left is:
|
After all, it seems that it is impossible to receive multicast messages from a socket directly binded to a specific interface. This makes things alot more complicated... The solution ciao, bonjour-js, mdns-js, etc. have all chosen is the first method:
However, as ciao states, this is leaky! and kind of defeats the whole purpose of the point of binding to each interface individually! https://github.com/homebridge/ciao/blob/a294fce273b19cac06fbc5dcdbb8db5e77caa68d/src/MDNSServer.ts#L518 The second option seems more sane:
However, the obvious caveat is that we can't receive unicast messages. My plan is just to focus on multicast for now. So we can bind onto the multicast group address, then use setMulticastInterface and addMembership targetting specific interface addresses in order to have a separate socket (and hence handler) for each interface. However, only multicast messages will be able to be received on those sockets. Hence, unicast sockets also need to be binded later if we need them... |
Does this mean 2 sockets for every IP address? |
yes, but that is if we decide to do unicast response, request. for now, i'm just focusing on not touching any of that @CMCDragonkai |
We're going to have to do it the way ciao does it. 1 socket per interface, but bound to wildcard. Make sure that the sockets will be able to join both the IPv4 multicast group and IPv6 multicast group. |
Some tests to consider:
|
|
On linux, due to node setting the |
Note that here https://github.com/clshortfuse/node-getsockethandleaddress it indicates that you can get the sockfd integer just by doing You should confirm if this fix is needed for macos. You'll still need to write the NAPI code to actually do something with that file descriptor number. The |
The intended behavior is that a binded socket to "0.0.0.0" or "::0", with IP_MULTICAST_ALL disabled, will not receive any multicast messages at all. It would seem, that disabling IP_MULTICAST_ALL works as intended on udp4 sockets. However, it seems that when disabling IPV6_MULTICAST_ALL, without calling addMembership, it works as intended. |
it seems that there are several options that add an ipv6 socket to a multicast group, being IPV6_JOIN_GROUP and IPV6_ADD_MEMBERSHIP. They all use the ipv6_mreq struct as a configuration option rather than the ip_mreq struct. The key difference between these is that ipv6_mreq takes in the interface index, whilst ip_mreq takes an interface ip address. Node, upon calling addMembership, will call uv_udp_set_membership with JOIN_GROUP, passing in the interface ip address.
On udp6, using either IPV6_ADD_MEMBERSHIP or IPV6_JOIN_GROUP, will for whatever reason, make your socket listen to multicast packets on all interfaces rather than just a singular specified one. The native code that i tested is: int AddMulticastMembership6(int sockfd, char* group, char* interface) {
struct ipv6_mreq mreq;
inet_pton(AF_INET6, group, &mreq.ipv6mr_multiaddr);
mreq.ipv6mr_interface = if_nametoindex(interface);
bool success = setsockopt(sockfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof(mreq)) >= 0;
return if_nametoindex(interface);
} |
i've found that IP_BLOCK_SOURCE also exists. this could be useful in filtering out our own traffic. However, we would need to implement a platform-agnostic solution if we wanted to use this across all platforms. For now, having a set ip to filter out seems fine to me. |
as a workaround to #1 (comment), i'm trying to just bind a unicast socket first, then binding all the multicast sockets after. This is done so that the first unicast socket will catch all of the necessary unicast traffic. I'm at the point of implementing this. However, even though i've made sure that the unicast socket is the first thing to be binded on a particular port, as soon as i bind other sockets, none of the sockets seem to be receiving any unicast traffic at all! I wonder if the first socket bound to a port on an interface with reuseaddr being true receiving all unicast traffiic is deterministic... |
on macos, tests run correctly, just some counted references are making the cleanup (afterAll) of MDNS hang. I've pinned it down to the sending of the goodbye packets, but i'm still figuring a solution |
on windows, it is not possible to bind to a multicast address like you can on any unix system. On windows systems, i am binding each multicast socket to "::" instead. This functionally is the same as binding to the multicast address in my case, as i'm binding a unicast socket before all the other multicast sockets are binded. Windows makes sure that only the first socket that you've bound will receive multicast traffic. |
Are you tracking all resources between start and stop? Always make sure to keep track of them. We already have problems with memory leaks and we have to be very strict here. |
Merged into staging now, doing the release. |
Is this fully addressed by MDNS? Are there still plans to handle Hairpinning, PMP and PCP? |
PMP and PCP should be done separately. Hairpinning not sure how that would be achieved. |
I created MatrixAI/Polykey#536 to track PCP/PMP via UPNP. I did find a project that could be wrapped around in JS to make use of. |
@amydevs please tick off everything that was done above too. |
Created by @CMCDragonkai
Specification
There are two types of Data Flow in the MDNS System, Polling (Pull), and Announcements/Responses (Push). When a Node joins the MDNS group, the records are pushed to all other nodes. However, for the joined node to discover other nodes, it needs to conduct polling queries that other nodes respond to.
Sending Queries
The MDNS spec states that query records can have additional records, but we won't care to do this as it isn't necessary.
Queries won't have any other records in the query record, much like a standard DNS packet (albeit an mdns query packet can contain multiple questions).
In the case that a responder is binded to 2 interfaces that are connected to the same network (such as a laptop with WiFi + ethernet connected), the queries asking for the ip for a hostname of the responder will receive multiple responses with different ip addresses.
This behavior is documented in: RFC 6762 14.
Control Flow
Unlike other mDNS libraries, we're going to use an AsyncIterator in order to have the consumer to have more control over the querying. An example of this would be:The query system has been decided to have it's runtime contained within
MDNS
rather than being consumer-driven. This means that scheduled background queries will have to be managed by a TaskManager (similar to polykey)Data Flow
Receiving Announcements/Responses (Pull)
Data Flow
Because queries are basically fire and forget, the main part comes in the form of receiving query responses from the multicast group. Hence, our querier needs to be able to collect records with a fan-in approach using a muxer that is reactive:
This can also be interpreted as a series of state transitions to completely build a service.
There also needs to be consideration that if the threshold for a muxer to complete is not reached, that additional queries are sent off in order to reach the finished state.
The decision tree for such would be as follows:
Control Flow
Instances of MDNS will extend EventTarget in order to emit events for service discovery/removal/etc.
The cache will be managed using a timer that is set to the soonest record TTL, rather than a timer for each record. The cache will also need to be an LRU in order to make sure that malicious responders cannot overwhelm it.
Sending Announcements
Control Flow
This will need to be experimented with a little. Currently the decisions are:
Types
Messages can be Queries or Announcements or Responses.
This can be expressed as:
Parser / Generator
The Parsing and Generation together are not isomorphic, as different parsed UInt8array packets can result in the same packet structure.
Every worker parser function will return the value wrapped in an object of this type:
The point of this is so that whatever hasn't been parsed get returned in
.remainder
so we don't keep track of the offset manually. This means that each worker function also needs to take in a second uint8array representing the original data structure.parsePacket(Uint8array): Packet
parseHeader(Uint8array): {id: ..., flags: PacketFlags, counts: {...}}
parseId(Uint8array): number
parseFlags(Uint8Array): PacketFlags
parseCount(Uint8Array): number
parseQuestionRecords(Uint8Array): {...}
parseQuestionRecord(Uint8Array): {...}
parseResourceRecords(Uint8Array): {...}
parseResourceRecord(Uint8Array): {...}
parseResourceRecordName(Uint8Array): string
parseResourceRecordType(Uint8Array): A/CNAME
parseResourceRecordClass(Uint8Array): IN
parseResourceRecordLength(Uint8array): number
parseResourceRecordData(Uint8array): {...}
parseARecordData(Uint8array): {...}
parseAAAARecordData(Uint8array): {...}
parseCNAMERecordData(Uint8array): {...}
parseSRVRecordData(Uint8array): {...}
parseTXTRecordData(Uint8array): Map<string, string>
parseOPTRecordData(Uint8array): {...}
parseNSECRecordData(Uint8array): {...}
ErrorDNSParse
- Generic error with message that contains information for different exceptions. Ie.id parse failed at ...
parseResourceRecordKey
andparseQuestionRecordKey
andparseRecordKey
-parseLabels
.generatePacket(Packet): UInt8Array
generateHeader(id, flags, counts...)
generateFlags({ ... }): Uint8Array
generateCount(number): Uint8Array
generateQuestionRecords(): Uint8Array
-flatMap(generateQuestion)
generateQuestionRecord(): Uint8Array
generateResourceRecords()
generateRecord(): Uint8array
-generateRecordName
- "abc.com" - ...RecordKeygenerateRecordType
- A/CNAMEgenerateRecordClass
- INgenerateRecordLength
generateRecordData
generateARecordData(string): Uint8array
generateAAAARecordData(string): Uint8array
generateCNAMERecordData(string): Uint8array
generateSRVRecordData(SRVRecordValue): Uint8array
generateTXTRecordData(Map<string, string>): Uint8array
generateOPTRecordData(Uint8array): Uint8array
generateNSECRecordData(): Uint8array
MDNS
MDNS
MDNS.query()
MDNS.registerService()
MDNS.unregisterService()
Testing
We can use two MDNS instances to interact with each other to test both query and respond on separate ports.
Additional Context
The following discussion from 'Refactoring Network Module' MR should be addressed:
@CMCDragonkai: (+3 comments)
https://news.ycombinator.com/item?id=8229792
https://blog.apnic.net/2022/05/03/how-nat-traversal-works-concerning-cgnats/
Manual Testing of
testnet.polykey.io
Polykey#487 (comment)Manual Testing of
testnet.polykey.io
Polykey#487 (comment)https://support.citrix.com/article/CTX205483/how-to-accommodate-hairpinning-behaviour-in-netscaler
mDNS RFC https://datatracker.ietf.org/doc/html/rfc6762
DNS-SD RFC https://datatracker.ietf.org/doc/html/rfc6763
Domain Names RFC https://datatracker.ietf.org/doc/html/rfc1035
Extension Mechanisms for DNS RFC https://datatracker.ietf.org/doc/html/rfc6891
NSEC RFC https://datatracker.ietf.org/doc/html/rfc3845
Tasks
The text was updated successfully, but these errors were encountered: