AdGuardHome/internal/dnsforward/util.go
Ainar Garipov 48d702f76a Pull request: all: fix client custom upstream comments
Updates #2947.

Squashed commit of the following:

commit 498a05459b1aa00bcffee490acfeecb567025971
Merge: 6a7a2f87 21e2c419
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Tue Apr 13 13:40:29 2021 +0300

    Merge branch 'master' into 2947-cli-ups-comment

commit 6a7a2f87cfd2bdd829b82889890511fef8d84b9b
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Tue Apr 13 13:34:28 2021 +0300

    all: imp code, tests

commit abc0be239f69cfc3e7d0cde2fc952d9157b2cd5d
Merge: 82fb3fcb 6410feeb
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Tue Apr 13 13:17:09 2021 +0300

    Merge branch 'master' into 2947-cli-ups-comment

commit 82fb3fcb49cbc8d439cb5959c1cb84ae49b2257e
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Mon Apr 12 22:13:41 2021 +0300

    all: fix client custom upstream comments
2021-04-13 13:44:29 +03:00

69 lines
1.4 KiB
Go

package dnsforward
import (
"net"
"sort"
"strings"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
)
// IPFromAddr gets IP address from addr.
func IPFromAddr(addr net.Addr) (ip net.IP) {
switch addr := addr.(type) {
case *net.UDPAddr:
return addr.IP
case *net.TCPAddr:
return addr.IP
}
return nil
}
// IPStringFromAddr extracts IP address from net.Addr.
// Note: we can't use net.SplitHostPort(a.String()) because of IPv6 zone:
// https://github.com/AdguardTeam/AdGuardHome/internal/issues/1261
func IPStringFromAddr(addr net.Addr) (ipStr string) {
if ip := IPFromAddr(addr); ip != nil {
return ip.String()
}
return ""
}
// Find value in a sorted array
func findSorted(ar []string, val string) int {
i := sort.SearchStrings(ar, val)
if i == len(ar) || ar[i] != val {
return -1
}
return i
}
func isWildcard(host string) bool {
return len(host) >= 2 &&
host[0] == '*' && host[1] == '.'
}
// Return TRUE if host name matches a wildcard pattern
func matchDomainWildcard(host, wildcard string) bool {
return isWildcard(wildcard) &&
strings.HasSuffix(host, wildcard[1:])
}
// Return TRUE if client's SNI value matches DNS names from certificate
func matchDNSName(dnsNames []string, sni string) bool {
if aghnet.ValidateDomainName(sni) != nil {
return false
}
if findSorted(dnsNames, sni) != -1 {
return true
}
for _, dn := range dnsNames {
if matchDomainWildcard(sni, dn) {
return true
}
}
return false
}