Skip to content

Commit

Permalink
wip: Try to match against IPv6 before falling back
Browse files Browse the repository at this point in the history
  • Loading branch information
heyvito committed May 16, 2023
1 parent 0334625 commit cdc22e9
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions pkg/hostagent/port.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,39 @@ func hostAddress(rule limayaml.PortForward, guest api.IPPort) string {
return host.String()
}

func tcpRuleIsWithinBounds(guest api.IPPort, rule limayaml.PortForward) bool {
if rule.GuestSocket != "" {
// Not TCP
return false
}

// Check if `guest.Port` is within `rule.GuestPortRange`
return guest.Port >= rule.GuestPortRange[0] && guest.Port <= rule.GuestPortRange[1]
}

func (pf *portForwarder) forwardingAddresses(guest api.IPPort) (hostAddr string, guestAddr string) {
// Check if it matches new IPv6 rule, otherwise fallback to the pre-IPv6 checks to maintain
// compatibility
for _, rule := range pf.rules {
if rule.GuestSocket != "" {
if !tcpRuleIsWithinBounds(guest, rule) {
continue
}
if guest.Port < rule.GuestPortRange[0] || guest.Port > rule.GuestPortRange[1] {

// guest.IP and HostIP must be either :: or 0.0.0.0, and be forwarded to the same family on HostIP
if guest.IP.IsUnspecified() && rule.HostIP.IsUnspecified() && ((guest.IP.To4() == nil) == (rule.HostIP.To4() == nil)) {
return hostAddress(rule, guest), guest.String()
}
}

// Before giving up, try to match against the old rule set
for _, rule := range pf.rules {
if !tcpRuleIsWithinBounds(guest, rule) {
continue
}

switch {
case guest.IP.IsUnspecified():
case guest.IP.Equal(rule.GuestIP):
case guest.IP.IsUnspecified() && rule.GuestIP.IsUnspecified() && ((guest.IP.To4() == nil) == (rule.HostIP.To4() == nil)):
case guest.IP.Equal(net.IPv6loopback) && rule.GuestIP.Equal(api.IPv4loopback1):
case rule.GuestIP.IsUnspecified() && !rule.GuestIPMustBeZero:
// When GuestIPMustBeZero is true, then 0.0.0.0 must be an exact match, which is already
Expand All @@ -67,6 +88,7 @@ func (pf *portForwarder) forwardingAddresses(guest api.IPPort) (hostAddr string,
}
return hostAddress(rule, guest), guest.String()
}

return "", guest.String()
}

Expand Down

0 comments on commit cdc22e9

Please sign in to comment.