Skip to content

Commit

Permalink
Fixing issue #786 - matchingHostNoGlob sometimes returns incorrect host
Browse files Browse the repository at this point in the history
Moves logic for reversing hosts / ports to get most specific match into
separate method

Calls this same method from both matchingHost and matchingHostNoGlob
  • Loading branch information
nathanejohnson committed Sep 9, 2020
1 parent 205ad55 commit a6c2549
Showing 1 changed file with 24 additions and 20 deletions.
44 changes: 24 additions & 20 deletions route/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,25 +339,7 @@ func (t Table) matchingHosts(req *http.Request, globCache *GlobCache) (hosts []s
}
}

if len(hosts) < 2 {
return
}

// Issue 506: multiple glob patterns hosts in wrong order
//
// DNS names have their most specific part at the front. In order to sort
// them from most specific to least specific a lexicographic sort will
// return the wrong result since it sorts by host name. *.foo.com will come
// before *.a.foo.com even though the latter is more specific. To achieve
// the correct result we need to reverse the strings, sort them and then
// reverse them again.
for i, h := range hosts {
hosts[i] = ReverseHostPort(h)
}
sort.Sort(sort.Reverse(sort.StringSlice(hosts)))
for i, h := range hosts {
hosts[i] = ReverseHostPort(h)
}
hosts = sortHostsReverHostPort(hosts)
return
}

Expand All @@ -372,12 +354,34 @@ func (t Table) matchingHostNoGlob(req *http.Request) (hosts []string) {
normpat := normalizeHost(pattern, req.TLS != nil)
if normpat == host {
hosts = append(hosts, strings.ToLower(pattern))
return
}
}
hosts = sortHostsReverHostPort(hosts)
return
}

func sortHostsReverHostPort(hosts []string) []string {
// Issue 506: multiple glob patterns hosts in wrong order
//
// DNS names have their most specific part at the front. In order to sort
// them from most specific to least specific a lexicographic sort will
// return the wrong result since it sorts by host name. *.foo.com will come
// before *.a.foo.com even though the latter is more specific. To achieve
// the correct result we need to reverse the strings, sort them and then
// reverse them again.
if len(hosts) < 2 {
return hosts
}
for i, h := range hosts {
hosts[i] = ReverseHostPort(h)
}
sort.Sort(sort.Reverse(sort.StringSlice(hosts)))
for i, h := range hosts {
hosts[i] = ReverseHostPort(h)
}
return hosts
}

// ReverseHostPort returns its argument string reversed rune-wise left to
// right. If s includes a port, only the host part is reversed.
func ReverseHostPort(s string) string {
Expand Down

0 comments on commit a6c2549

Please sign in to comment.