2021-12-05 14:21:05 +00:00
|
|
|
package dns
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"strings"
|
2022-11-12 19:37:20 +00:00
|
|
|
"time"
|
2021-12-05 14:21:05 +00:00
|
|
|
|
2024-05-26 20:05:46 +00:00
|
|
|
"github.com/hashicorp/golang-lru/v2/expirable"
|
2021-12-05 14:21:05 +00:00
|
|
|
)
|
|
|
|
|
2024-05-26 20:05:46 +00:00
|
|
|
const (
|
|
|
|
lookupCacheValidity = 30 * time.Second
|
|
|
|
defaultPagesRepo = "pages"
|
|
|
|
)
|
2022-11-12 19:37:20 +00:00
|
|
|
|
2024-05-26 20:05:46 +00:00
|
|
|
// TODO(#316): refactor to not use global variables
|
|
|
|
var lookupCache *expirable.LRU[string, string] = expirable.NewLRU[string, string](4096, nil, lookupCacheValidity)
|
2023-02-14 03:03:00 +00:00
|
|
|
|
2021-12-05 14:21:05 +00:00
|
|
|
// GetTargetFromDNS searches for CNAME or TXT entries on the request domain ending with MainDomainSuffix.
|
|
|
|
// If everything is fine, it returns the target data.
|
2024-05-26 20:05:46 +00:00
|
|
|
func GetTargetFromDNS(domain, mainDomainSuffix, firstDefaultBranch string) (targetOwner, targetRepo, targetBranch string) {
|
2021-12-05 14:21:05 +00:00
|
|
|
// Get CNAME or TXT
|
|
|
|
var cname string
|
|
|
|
var err error
|
2024-05-26 20:05:46 +00:00
|
|
|
|
|
|
|
if entry, ok := lookupCache.Get(domain); ok {
|
|
|
|
cname = entry
|
2021-12-05 14:21:05 +00:00
|
|
|
} else {
|
|
|
|
cname, err = net.LookupCNAME(domain)
|
|
|
|
cname = strings.TrimSuffix(cname, ".")
|
|
|
|
if err != nil || !strings.HasSuffix(cname, mainDomainSuffix) {
|
|
|
|
cname = ""
|
|
|
|
// TODO: check if the A record matches!
|
|
|
|
names, err := net.LookupTXT(domain)
|
|
|
|
if err == nil {
|
|
|
|
for _, name := range names {
|
2023-02-10 01:44:44 +00:00
|
|
|
name = strings.TrimSuffix(strings.TrimSpace(name), ".")
|
2021-12-05 14:21:05 +00:00
|
|
|
if strings.HasSuffix(name, mainDomainSuffix) {
|
|
|
|
cname = name
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-05-26 20:05:46 +00:00
|
|
|
_ = lookupCache.Add(domain, cname)
|
2021-12-05 14:21:05 +00:00
|
|
|
}
|
|
|
|
if cname == "" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
cnameParts := strings.Split(strings.TrimSuffix(cname, mainDomainSuffix), ".")
|
|
|
|
targetOwner = cnameParts[len(cnameParts)-1]
|
|
|
|
if len(cnameParts) > 1 {
|
|
|
|
targetRepo = cnameParts[len(cnameParts)-2]
|
|
|
|
}
|
|
|
|
if len(cnameParts) > 2 {
|
|
|
|
targetBranch = cnameParts[len(cnameParts)-3]
|
|
|
|
}
|
|
|
|
if targetRepo == "" {
|
2023-02-14 03:03:00 +00:00
|
|
|
targetRepo = defaultPagesRepo
|
2021-12-05 14:21:05 +00:00
|
|
|
}
|
2023-02-14 03:03:00 +00:00
|
|
|
if targetBranch == "" && targetRepo != defaultPagesRepo {
|
|
|
|
targetBranch = firstDefaultBranch
|
2021-12-05 14:21:05 +00:00
|
|
|
}
|
|
|
|
// if targetBranch is still empty, the caller must find the default branch
|
|
|
|
return
|
|
|
|
}
|