From 960412a335729869b063b7101ece86367f35c882 Mon Sep 17 00:00:00 2001 From: Adrien Raffin-Caboisse Date: Mon, 21 Feb 2022 09:02:27 +0100 Subject: [PATCH] fix(machines): simplify complex if check This should fix the performance issue with computation of `dst` variable. It's also easier to read now. --- machine.go | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/machine.go b/machine.go index edebe031..45434075 100644 --- a/machine.go +++ b/machine.go @@ -132,8 +132,8 @@ func (h *Headscale) ListAllMachines() ([]Machine, error) { return machines, nil } -func containsAddresses(inputs []string, addrs MachineAddresses) bool { - for _, addr := range addrs.ToStringSlice() { +func containsAddresses(inputs []string, addrs []string) bool { + for _, addr := range addrs { if containsString(inputs, addr) { return true } @@ -142,6 +142,11 @@ func containsAddresses(inputs []string, addrs MachineAddresses) bool { return false } +// matchSourceAndDestinationWithRule +func matchSourceAndDestinationWithRule(ruleSources []string, ruleDestinations []string, source []string, destination []string) bool { + return containsAddresses(ruleSources, source) && containsAddresses(ruleDestinations, destination) +} + // getFilteredByACLPeerss should return the list of peers authorized to be accessed from machine. func (h *Headscale) getFilteredByACLPeers(machine *Machine) (Machines, error) { log.Trace(). @@ -180,9 +185,9 @@ func (h *Headscale) getFilteredByACLPeers(machine *Machine) (Machines, error) { for _, d := range rule.DstPorts { dst = append(dst, d.IP) } - if (containsAddresses(rule.SrcIPs, machine.IPAddresses) && (containsAddresses(dst, peer.IPAddresses) || containsString(dst, "*"))) || ( - // open return path - containsAddresses(rule.SrcIPs, peer.IPAddresses) && containsAddresses(dst, machine.IPAddresses)) { + if matchSourceAndDestinationWithRule(rule.SrcIPs, dst, machine.IPAddresses.ToStringSlice(), peer.IPAddresses.ToStringSlice()) || // match source and destination + matchSourceAndDestinationWithRule(rule.SrcIPs, dst, machine.IPAddresses.ToStringSlice(), []string{"*"}) || // match source and all destination + matchSourceAndDestinationWithRule(rule.SrcIPs, dst, peer.IPAddresses.ToStringSlice(), machine.IPAddresses.ToStringSlice()) { // match return path peers[peer.ID] = peer } }