├── .gitignore
├── .dockerignore
├── go.mod
├── Dockerfile
├── .github
└── workflows
│ ├── go.yml
│ └── lint.yml
├── .cspell.json
├── Makefile
├── zone
├── root.go
├── parse.go
└── zone.go
├── psl
└── psl.go
├── release.mk
├── README.md
├── resolver
├── cache_test.go
├── cache.go
├── context_test.go
├── resolver_test.go
└── resolver.go
├── save
└── savezone.go
├── main.go
├── go.sum
├── status
└── status.go
├── axfr.go
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | allxfr
2 | zones/
3 |
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | allxfr
2 | Dockerfile
3 | .git*
4 | unbound/
5 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/lanrat/allxfr
2 |
3 | go 1.23.0
4 |
5 | require (
6 | github.com/miekg/dns v1.1.67
7 | github.com/weppos/publicsuffix-go v0.40.2
8 | golang.org/x/sync v0.16.0
9 | )
10 |
11 | require (
12 | golang.org/x/mod v0.26.0 // indirect
13 | golang.org/x/net v0.42.0 // indirect
14 | golang.org/x/sys v0.34.0 // indirect
15 | golang.org/x/text v0.27.0 // indirect
16 | golang.org/x/tools v0.35.0 // indirect
17 | )
18 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | # build stage
2 | FROM golang:alpine AS build-env
3 | RUN apk update && apk add --no-cache make git
4 |
5 | # Accept VERSION as a build argument
6 | ARG VERSION
7 | ENV VERSION=${VERSION}
8 |
9 | WORKDIR /go/app/
10 | COPY go.mod go.sum ./
11 | RUN go mod download
12 |
13 | COPY . .
14 | RUN make
15 |
16 | # final stage
17 | FROM alpine
18 |
19 | COPY --from=build-env /go/app/allxfr /bin/allxfr
20 |
21 | USER 1000
22 |
23 | ENTRYPOINT ["allxfr"]
24 |
--------------------------------------------------------------------------------
/.github/workflows/go.yml:
--------------------------------------------------------------------------------
1 | name: Go
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | jobs:
10 |
11 | build:
12 | name: Build and Test
13 | runs-on: ubuntu-latest
14 | steps:
15 | - uses: actions/checkout@v4
16 |
17 | - uses: actions/setup-go@v5
18 | with:
19 | go-version-file: go.mod
20 |
21 | - name: Get dependencies
22 | run: make deps
23 |
24 | - name: Run tests
25 | run: make test
26 |
27 | - name: Build
28 | run: make
29 |
--------------------------------------------------------------------------------
/.github/workflows/lint.yml:
--------------------------------------------------------------------------------
1 | name: Lint
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | permissions:
10 | contents: read
11 | pull-requests: read
12 |
13 | jobs:
14 | golangci:
15 | name: lint
16 | runs-on: ubuntu-latest
17 | steps:
18 | - uses: actions/checkout@v4
19 |
20 | - uses: actions/setup-go@v5
21 | with:
22 | go-version-file: go.mod
23 |
24 | - name: golangci-lint
25 | uses: golangci/golangci-lint-action@v8
26 | with:
27 | version: latest
--------------------------------------------------------------------------------
/.cspell.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2",
3 | "ignorePaths": [],
4 | "dictionaryDefinitions": [],
5 | "dictionaries": [],
6 | "words": [
7 | "AAAAIPs",
8 | "allxfr",
9 | "AXFR",
10 | "errgroup",
11 | "gofmt",
12 | "golangci",
13 | "GOPROXY",
14 | "hostnames",
15 | "installsuffix",
16 | "ixfr",
17 | "lanrat",
18 | "miekg",
19 | "Minttl",
20 | "NOERROR",
21 | "NXDOMAIN",
22 | "publicsuffix",
23 | "qtype",
24 | "Rcode",
25 | "Rrtype",
26 | "staticcheck",
27 | "trimpath",
28 | "weppos",
29 | "zonefile"
30 | ],
31 | "ignoreWords": [],
32 | "import": []
33 | }
34 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | default: allxfr
2 |
3 | include release.mk
4 |
5 | # creates static binaries
6 | CC := CGO_ENABLED=0 go build -ldflags "-w -s -X main.version=${VERSION}" -trimpath -a -installsuffix cgo
7 |
8 | SOURCES := $(shell find . -type f -name '*.go')
9 | BIN := allxfr
10 |
11 | .PHONY: all fmt docker clean deps update-deps
12 |
13 | docker: Dockerfile $(SOURCES) go.mod go.sum
14 | docker build --build-arg VERSION=${VERSION} -t="lanrat/allxfr" .
15 |
16 | $(BIN): $(SOURCES) go.mod go.sum
17 | $(CC) -o $@
18 |
19 | check:
20 | golangci-lint run
21 | staticcheck -checks all ./...
22 |
23 | update-deps: go.mod
24 | GOPROXY=direct go get -u ./...
25 | go mod tidy
26 |
27 | deps: go.mod
28 | go mod download
29 |
30 | test:
31 | go test -timeout 15s -v ./...
32 |
33 | clean:
34 | rm $(BIN)
35 |
36 | fmt:
37 | go fmt .
38 |
39 |
--------------------------------------------------------------------------------
/zone/root.go:
--------------------------------------------------------------------------------
1 | package zone
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/miekg/dns"
7 | )
8 |
9 | // RootAXFR performs a zone transfer against a root nameserver to obtain the root zone.
10 | // It connects to the specified nameserver on port 53 and requests the root zone (".").
11 | // Returns a Zone containing all the NS, A, and AAAA records from the root zone.
12 | func RootAXFR(ns string) (Zone, error) {
13 | m := new(dns.Msg)
14 | m.SetQuestion(".", dns.TypeAXFR)
15 | t := new(dns.Transfer)
16 |
17 | var root Zone
18 | env, err := t.In(m, fmt.Sprintf("%s:53", ns))
19 | if err != nil {
20 | return root, fmt.Errorf("transfer error from %v: %w", ns, err)
21 | }
22 | for e := range env {
23 | if e.Error != nil {
24 | return root, fmt.Errorf("transfer envelope error from %v: %w", ns, e.Error)
25 | }
26 | for _, r := range e.RR {
27 | root.AddRecord(r)
28 | }
29 | }
30 | return root, nil
31 | }
32 |
--------------------------------------------------------------------------------
/zone/parse.go:
--------------------------------------------------------------------------------
1 | // Package zone provides functionality for parsing and managing DNS zone files.
2 | package zone
3 |
4 | import (
5 | "compress/gzip"
6 | "io"
7 | "os"
8 | "strings"
9 |
10 | "github.com/miekg/dns"
11 | )
12 |
13 | // ParseZoneFile parses a DNS zone file and returns a Zone containing the records.
14 | // It supports both plain text and gzip-compressed zone files (detected by .gz extension).
15 | // The function extracts NS, A, and AAAA records to build the zone structure.
16 | func ParseZoneFile(filename string) (Zone, error) {
17 | var z Zone
18 | var fileReader io.Reader
19 | file, err := os.Open(filename)
20 | fileReader = file
21 | if err != nil {
22 | return z, err
23 | }
24 | defer func() { _ = file.Close() }()
25 | if strings.HasSuffix(filename, ".gz") {
26 | gz, err := gzip.NewReader(file)
27 | if err != nil {
28 | return z, err
29 | }
30 | fileReader = gz
31 | defer func() { _ = gz.Close() }()
32 | }
33 | zp := dns.NewZoneParser(fileReader, "", "")
34 | for rr, ok := zp.Next(); ok; rr, ok = zp.Next() {
35 | z.AddRecord(rr)
36 | }
37 |
38 | if err := zp.Err(); err != nil {
39 | return z, err
40 | }
41 | return z, nil
42 | }
43 |
--------------------------------------------------------------------------------
/psl/psl.go:
--------------------------------------------------------------------------------
1 | // Package psl provides functionality to fetch domains from the Public Suffix List.
2 | package psl
3 |
4 | import (
5 | "context"
6 | "net/http"
7 | "time"
8 |
9 | "github.com/miekg/dns"
10 | "github.com/weppos/publicsuffix-go/publicsuffix"
11 | )
12 |
13 | const (
14 | pslURL = "https://publicsuffix.org/list/public_suffix_list.dat"
15 | pslTimeout = 30 * time.Second
16 | )
17 |
18 | // GetDomains fetches and parses the Public Suffix List to extract domain names.
19 | // It downloads the PSL from publicsuffix.org, parses the rules (excluding private domains),
20 | // converts IDN domains to ASCII, and returns them as fully qualified domain names.
21 | // The function includes timeout handling to prevent indefinite blocking.
22 | func GetDomains() ([]string, error) {
23 | ctx, cancel := context.WithTimeout(context.Background(), pslTimeout)
24 | defer cancel()
25 |
26 | req, err := http.NewRequestWithContext(ctx, "GET", pslURL, nil)
27 | if err != nil {
28 | return nil, err
29 | }
30 |
31 | client := &http.Client{Timeout: pslTimeout}
32 | resp, err := client.Do(req)
33 | if err != nil {
34 | return nil, err
35 | }
36 | defer func() { _ = resp.Body.Close() }()
37 |
38 | list := publicsuffix.NewList()
39 | options := &publicsuffix.ParserOption{
40 | PrivateDomains: false,
41 | }
42 | rules, err := list.Load(resp.Body, options)
43 | if err != nil {
44 | return nil, err
45 | }
46 |
47 | out := make([]string, 0, len(rules))
48 | for _, rule := range rules {
49 | if rule.Type != publicsuffix.ExceptionType {
50 | domain, err := publicsuffix.ToASCII(rule.Value)
51 | if err != nil {
52 | return out, err
53 | }
54 | out = append(out, dns.Fqdn(domain))
55 | }
56 | }
57 | return out, nil
58 | }
59 |
--------------------------------------------------------------------------------
/release.mk:
--------------------------------------------------------------------------------
1 | # Get the current version from git.
2 | # `git describe` will use the most recent tag.
3 | # `--tags` ensures any tag is considered, not just annotated ones.
4 | # `--always` ensures that if no tags are present, the commit hash is used.
5 | # `--dirty` will append "-dirty" if the working directory has uncommitted changes.
6 | VERSION ?= $(shell git describe --tags --always --dirty)
7 |
8 | # Release target to create a new semantic version tag
9 | .PHONY: release-tag
10 | release-tag: check
11 | # This shell 'if' statement runs at execution time, not parse time.
12 | @if [ -z "$(BUMP)" ]; then \
13 | echo "Error: BUMP is not set. Usage: make release BUMP=patch|minor|major"; \
14 | exit 1; \
15 | fi
16 |
17 | # 1. Check for a clean working directory
18 | @if ! git diff --quiet; then \
19 | echo "Error: Working directory is not clean. Commit or stash changes before releasing."; \
20 | exit 1; \
21 | fi
22 |
23 | # 2. Get the latest git tag, or start at v0.0.0
24 | @CURRENT_TAG=$$(git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0"); \
25 | CURRENT_VERSION=$$(echo $$CURRENT_TAG | sed 's/^v//'); \
26 | MAJOR=$$(echo $$CURRENT_VERSION | cut -d. -f1); \
27 | MINOR=$$(echo $$CURRENT_VERSION | cut -d. -f2); \
28 | PATCH=$$(echo $$CURRENT_VERSION | cut -d. -f3); \
29 | \
30 | if [ "$(BUMP)" = "patch" ]; then \
31 | PATCH=$$((PATCH + 1)); \
32 | elif [ "$(BUMP)" = "minor" ]; then \
33 | MINOR=$$((MINOR + 1)); \
34 | PATCH=0; \
35 | elif [ "$(BUMP)" = "major" ]; then \
36 | MAJOR=$$((MAJOR + 1)); \
37 | MINOR=0; \
38 | PATCH=0; \
39 | else \
40 | echo "Error: Invalid BUMP value. Use 'patch', 'minor', or 'major'."; \
41 | exit 1; \
42 | fi; \
43 | \
44 | NEW_TAG="v$${MAJOR}.$${MINOR}.$${PATCH}"; \
45 | echo "Current version: $$CURRENT_TAG"; \
46 | echo "Creating new version: $$NEW_TAG"; \
47 | git tag $$NEW_TAG; \
48 | git push origin $$NEW_TAG;
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ALLXFR
2 |
3 | ## AXFR all the things!
4 |
5 |
6 |
7 | This tool performs a [zone transfer (AXFR)](https://en.wikipedia.org/wiki/DNS_zone_transfer) against the root zone servers to obtain the [root zone file](https://www.iana.org/domains/root/files). And then attempts opportunistic zone transfers for every IP for every nameserver for a given zone. Additionally, each NS/A/AAAA record is also re-queried to find additional servers or IPs not included as root glue.
8 |
9 | Most zones do not allow zone transfers, however a few do. Sometimes only on a single IP for a given nameserver and not the others, and sometimes only for servers or IPs that are authoritative but not included in the root zones. This tool will try them all and save every successful transfer.
10 |
11 | This tool works best on an IPv4/IPv6 dual stack internet connection.
12 |
13 | Providing a zone file with the `-zonefile` flag will attempt a transfer with the domains and sub-domains in the zone file provided.
14 |
15 | TLDs in the [Public Suffix List](https://publicsuffix.org/) can be attempted as well with the `-psl` flag.
16 |
17 | ## Example
18 |
19 | ```console
20 | ./allxfr -dry-run
21 | ROOT g.root-servers.net. xfr size: 22017 records in 1.334s
22 | mr. ns-mr.nic.tn. (41.228.63.70) xfr size: 444 records in 337ms
23 | sl. ns1.neoip.com. (45.83.41.38) xfr size: 455 records in 592ms
24 | sy. ns1.tld.sy. (82.137.200.85) xfr size: 1594 records in 870ms
25 | cd. ns-root-2.scpt-network.com. (41.79.235.67) xfr size: 497 records in 598ms
26 | my. a.nic.my. (103.44.108.53) xfr size: 1592 records in 608ms
27 | mq. ns1-mq.mediaserv.net. (213.16.20.3) xfr size: 1541 records in 299ms
28 | td. nsa.nic.td. (154.68.159.246) xfr size: 492 records in 1.821s
29 | gp. ns2.nic.gp. (193.218.114.34) xfr size: 1578 records in 195ms
30 | xn--54b7fta0cc. bayanno.btcl.net.bd. (180.211.212.213) xfr size: 915 records in 728ms
31 | xn--ogbpf8fl. ns1.tld.sy. (82.137.200.85) xfr size: 271 records in 460ms
32 | xn--90ae. a.nic.bg. (2a02:6a80::192:92:129:99) xfr size: 305 records in 326ms
33 | cv. cv01.dns.pt. (185.39.208.18) xfr size: 507 records in 333ms
34 | bd. surma.btcl.net.bd. (203.112.194.232) xfr size: 52 records in 486ms
35 | rw. ns1.ricta.org.rw. (196.49.7.188) xfr size: 1515 records in 1.269s
36 | gf. ns1-mq.mediaserv.net. (213.16.20.3) xfr size: 1531 records in 304ms
37 | bn. ns2.bnnic.bn. (202.93.214.163) xfr size: 79 records in 395ms
38 | tj. ns2.tojikiston.com. (193.111.11.4) xfr size: 1690 records in 998ms
39 | pg. ns1.tiare.net.pg. (202.165.192.23) xfr size: 447 records in 409ms
40 | mw. domwe.sdn.mw. (41.87.5.162) xfr size: 1538 records in 938ms
41 | xn--j1amh. tier1.num.net.ua. (193.110.163.134) xfr size: 1055 records in 1.349s
42 | sv. cir.red.sv. (168.243.254.1) xfr size: 1514 records in 883ms
43 | 21 / 1516 transfered in 3m29.92
44 | ```
45 |
46 | ## Usage
47 |
48 | ```console
49 | Usage of ./allxfr:
50 | -dry-run
51 | only test if xfr is allowed by retrieving one envelope
52 | -ixfr
53 | attempt an IXFR instead of AXFR
54 | -out string
55 | directory to save found zones in (default "zones")
56 | -overwrite
57 | if zone already exists on disk, overwrite it with newer data
58 | -parallel uint
59 | number of parallel zone transfers to perform (default 10)
60 | -psl
61 | attempt AXFR from zones listed in the public suffix list
62 | -retry int
63 | number of times to retry failed operations (default 3)
64 | -save-all
65 | attempt AXFR from every nameserver for a given zone and save all answers
66 | -status-listen string
67 | enable HTTP status server on specified [IP:]port (e.g., '8080', '127.0.0.1:8080', '[::1]:8080')
68 | -verbose
69 | enable verbose output
70 | -version
71 | print version and exit
72 | -zonefile string
73 | use the provided zonefile instead of getting the root zonefile
74 | ```
75 |
76 | ## Building
77 |
78 | ```console
79 | go build
80 | ```
81 |
--------------------------------------------------------------------------------
/zone/zone.go:
--------------------------------------------------------------------------------
1 | package zone
2 |
3 | import (
4 | "fmt"
5 | "net"
6 | "strings"
7 |
8 | "github.com/miekg/dns"
9 | )
10 |
11 | // Zone contains the nameservers and nameserver IPs in a zone.
12 | // It maintains mappings between domain names and their nameservers,
13 | // as well as nameserver hostnames to their IP addresses.
14 | type Zone struct {
15 | // NS maps domain names to their authoritative nameservers
16 | NS map[string][]string
17 | // IP maps nameserver hostnames to their IPv4 and IPv6 addresses
18 | IP map[string][]net.IP
19 | // Records tracks the total number of records added to the zone
20 | Records int64
21 | }
22 |
23 | // AddRecord adds NS, A, and AAAA records to the zone.
24 | // It extracts nameserver and IP information from DNS resource records
25 | // and updates the zone's internal mappings accordingly.
26 | func (z *Zone) AddRecord(r dns.RR) {
27 | switch t := r.(type) {
28 | case *dns.A:
29 | z.AddIP(t.Hdr.Name, t.A)
30 | case *dns.AAAA:
31 | z.AddIP(t.Hdr.Name, t.AAAA)
32 | case *dns.NS:
33 | z.AddNS(t.Hdr.Name, t.Ns)
34 | }
35 | }
36 |
37 | // GetNameChan returns a channel that yields all domain names in the zone.
38 | // It skips the root zone (".") and .arpa domains as they are not suitable
39 | // for zone transfer attempts. The channel is closed when all domains are sent.
40 | func (z *Zone) GetNameChan() chan string {
41 | out := make(chan string)
42 | go func() {
43 | for domain := range z.NS {
44 | // skip root & arpa
45 | if domain == "." {
46 | continue
47 | }
48 | if domain == "arpa." || strings.HasSuffix(domain, ".arpa.") {
49 | continue
50 | }
51 | out <- domain
52 | }
53 | close(out)
54 | }()
55 | return out
56 | }
57 |
58 | // CountNS returns the number of unique domain names that have nameservers in the zone.
59 | func (z *Zone) CountNS() int {
60 | return len(z.NS)
61 | }
62 |
63 | // AddNS adds a nameserver for a domain to the zone.
64 | // Domain names are normalized to lowercase. If nameserver is empty,
65 | // only the domain entry is created without adding a nameserver.
66 | func (z *Zone) AddNS(domain, nameserver string) {
67 | domain = strings.ToLower(domain)
68 | if z.NS == nil {
69 | z.NS = make(map[string][]string)
70 | }
71 | _, ok := z.NS[domain]
72 | if !ok {
73 | z.NS[domain] = make([]string, 0, 4)
74 | }
75 | if len(nameserver) > 0 {
76 | nameserver = strings.ToLower(nameserver)
77 | z.NS[domain] = append(z.NS[domain], nameserver)
78 | z.Records++
79 | }
80 | }
81 |
82 | // AddIP adds an IP address for a nameserver to the zone.
83 | // Nameserver names are normalized to lowercase. Both IPv4 and IPv6
84 | // addresses are supported and stored in the same slice.
85 | func (z *Zone) AddIP(nameserver string, ip net.IP) {
86 | nameserver = strings.ToLower(nameserver)
87 | if z.IP == nil {
88 | z.IP = make(map[string][]net.IP)
89 | }
90 | _, ok := z.IP[nameserver]
91 | if !ok {
92 | z.IP[nameserver] = make([]net.IP, 0, 4)
93 | }
94 | z.IP[nameserver] = append(z.IP[nameserver], ip)
95 | z.Records++
96 | }
97 |
98 | // Print outputs the zone structure to stdout in a simple format.
99 | // It displays all domains with their nameservers, followed by
100 | // all nameservers with their IP addresses.
101 | func (z *Zone) Print() {
102 | fmt.Println("NS:")
103 | for zone := range z.NS {
104 | fmt.Printf("%s\n", zone)
105 | for i := range z.NS[zone] {
106 | fmt.Printf("\t%s\n", z.NS[zone][i])
107 | }
108 | }
109 | fmt.Println("IP:")
110 | for ns := range z.IP {
111 | fmt.Printf("%s\n", ns)
112 | for i := range z.IP[ns] {
113 | fmt.Printf("\t%s\n", z.IP[ns][i])
114 | }
115 | }
116 | }
117 |
118 | // PrintTree outputs the zone structure to stdout in a hierarchical tree format.
119 | // It shows domains, their nameservers, and the IP addresses for each nameserver
120 | // in an indented tree structure for better readability.
121 | func (z *Zone) PrintTree() {
122 | fmt.Println("Zones:")
123 | for zone := range z.NS {
124 | fmt.Printf("%s\n", zone)
125 | for i := range z.NS[zone] {
126 | fmt.Printf("\t%s\n", z.NS[zone][i])
127 | for j := range z.IP[z.NS[zone][i]] {
128 | fmt.Printf("\t\t%s\n", z.IP[z.NS[zone][i]][j])
129 | }
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/resolver/cache_test.go:
--------------------------------------------------------------------------------
1 | package resolver
2 |
3 | import (
4 | "context"
5 | "net"
6 | "testing"
7 | "time"
8 |
9 | "github.com/miekg/dns"
10 | )
11 |
12 | func TestCacheBasicFunctionality(t *testing.T) {
13 | resolver := NewWithCacheSize(10, defaultQueryTimeout)
14 | domain := "google.com"
15 |
16 | ctx := context.Background()
17 |
18 | result1, err := resolver.Resolve(ctx, domain, dns.TypeA)
19 | if err != nil {
20 | t.Fatalf("Failed to resolve %s: %v", domain, err)
21 | }
22 |
23 | start := time.Now()
24 | result2, err := resolver.Resolve(ctx, domain, dns.TypeA)
25 | duration := time.Since(start)
26 |
27 | if err != nil {
28 | t.Fatalf("Failed to resolve cached %s: %v", domain, err)
29 | }
30 |
31 | if duration > 100*time.Millisecond {
32 | t.Errorf("Cached lookup took too long: %v", duration)
33 | }
34 |
35 | if len(result1.Answer) != len(result2.Answer) {
36 | t.Errorf("Cache returned different number of answers")
37 | }
38 | }
39 |
40 | func TestCacheTTLExpiry(t *testing.T) {
41 | cache := newDNSCache(10)
42 |
43 | result := &Result{
44 | Answer: []dns.RR{
45 | &dns.A{
46 | Hdr: dns.RR_Header{
47 | Name: "test.com.",
48 | Rrtype: dns.TypeA,
49 | Class: dns.ClassINET,
50 | Ttl: 1,
51 | },
52 | A: net.ParseIP("1.2.3.4"),
53 | },
54 | },
55 | }
56 |
57 | cache.put("test.com.:1", result, 1*time.Second)
58 |
59 | if cached, found := cache.get("test.com.:1"); !found {
60 | t.Error("Should find cached entry immediately")
61 | } else if len(cached.Answer) != 1 {
62 | t.Error("Cached result should have 1 answer")
63 | }
64 |
65 | time.Sleep(1100 * time.Millisecond)
66 |
67 | if _, found := cache.get("test.com.:1"); found {
68 | t.Error("Should not find expired cached entry")
69 | }
70 | }
71 |
72 | func TestCacheLRUEviction(t *testing.T) {
73 | cache := newDNSCache(2)
74 |
75 | result1 := &Result{Answer: []dns.RR{}}
76 | result2 := &Result{Answer: []dns.RR{}}
77 | result3 := &Result{Answer: []dns.RR{}}
78 |
79 | cache.put("key1", result1, 1*time.Hour)
80 | cache.put("key2", result2, 1*time.Hour)
81 | cache.put("key3", result3, 1*time.Hour)
82 |
83 | if _, found := cache.get("key1"); found {
84 | t.Error("key1 should have been evicted")
85 | }
86 |
87 | if _, found := cache.get("key2"); !found {
88 | t.Error("key2 should still be in cache")
89 | }
90 |
91 | if _, found := cache.get("key3"); !found {
92 | t.Error("key3 should still be in cache")
93 | }
94 | }
95 |
96 | func TestCacheLRUOrdering(t *testing.T) {
97 | cache := newDNSCache(3)
98 |
99 | result1 := &Result{Answer: []dns.RR{}}
100 | result2 := &Result{Answer: []dns.RR{}}
101 | result3 := &Result{Answer: []dns.RR{}}
102 | result4 := &Result{Answer: []dns.RR{}}
103 |
104 | cache.put("key1", result1, 1*time.Hour)
105 | cache.put("key2", result2, 1*time.Hour)
106 | cache.put("key3", result3, 1*time.Hour)
107 |
108 | cache.get("key1")
109 |
110 | cache.put("key4", result4, 1*time.Hour)
111 |
112 | if _, found := cache.get("key2"); found {
113 | t.Error("key2 should have been evicted (was least recently used)")
114 | }
115 |
116 | if _, found := cache.get("key1"); !found {
117 | t.Error("key1 should still be in cache (was accessed recently)")
118 | }
119 | }
120 |
121 | func TestCacheKeyGeneration(t *testing.T) {
122 | resolver := New()
123 |
124 | key1 := resolver.makeCacheKey("example.com.", dns.TypeA)
125 | key2 := resolver.makeCacheKey("example.com.", dns.TypeAAAA)
126 | key3 := resolver.makeCacheKey("test.com.", dns.TypeA)
127 |
128 | if key1 == key2 {
129 | t.Error("Different record types should generate different keys")
130 | }
131 |
132 | if key1 == key3 {
133 | t.Error("Different domains should generate different keys")
134 | }
135 |
136 | expected1 := "example.com.:1"
137 | if key1 != expected1 {
138 | t.Errorf("Expected key %s, got %s", expected1, key1)
139 | }
140 | }
141 |
142 | func TestCalculateTTL(t *testing.T) {
143 | resolver := New()
144 |
145 | result := &Result{
146 | Answer: []dns.RR{
147 | &dns.A{
148 | Hdr: dns.RR_Header{Ttl: 300},
149 | },
150 | &dns.A{
151 | Hdr: dns.RR_Header{Ttl: 600},
152 | },
153 | },
154 | Authority: []dns.RR{
155 | &dns.NS{
156 | Hdr: dns.RR_Header{Ttl: 200},
157 | },
158 | },
159 | }
160 |
161 | ttl := resolver.calculateTTL(result)
162 | expected := 200 * time.Second
163 |
164 | if ttl != expected {
165 | t.Errorf("Expected TTL %v, got %v", expected, ttl)
166 | }
167 |
168 | result.Authority[0].Header().Ttl = 30
169 | ttl = resolver.calculateTTL(result)
170 | expected = 60 * time.Second
171 |
172 | if ttl != expected {
173 | t.Errorf("Expected minimum TTL %v, got %v", expected, ttl)
174 | }
175 | }
176 |
--------------------------------------------------------------------------------
/resolver/cache.go:
--------------------------------------------------------------------------------
1 | package resolver
2 |
3 | import (
4 | "sync"
5 | "time"
6 | )
7 |
8 | const (
9 | defaultCacheSize = 1000
10 | )
11 |
12 | // cacheEntry represents a single cached DNS result with metadata.
13 | type cacheEntry struct {
14 | result *Result // The cached DNS query result
15 | expiry time.Time // When this cache entry expires
16 | lastUsed time.Time // When this entry was last accessed (for LRU)
17 | negative bool // true for NXDOMAIN/negative cache entries
18 | }
19 |
20 | // cacheNode is a node in the doubly-linked list used for LRU cache implementation.
21 | type cacheNode struct {
22 | key string // Cache key for this entry
23 | entry *cacheEntry // The cached data
24 | prev *cacheNode // Previous node in the linked list
25 | next *cacheNode // Next node in the linked list
26 | }
27 |
28 | // dnsCache implements an LRU cache for DNS query results.
29 | // It uses a combination of a hash map for O(1) lookups and a doubly-linked
30 | // list for O(1) LRU operations.
31 | type dnsCache struct {
32 | mutex sync.RWMutex // Protects all cache operations
33 | capacity int // Maximum number of entries to store
34 | cache map[string]*cacheNode // Hash map for fast lookups
35 | head *cacheNode // Head of doubly-linked list (most recent)
36 | tail *cacheNode // Tail of doubly-linked list (least recent)
37 | }
38 |
39 | // newDNSCache creates a new DNS cache with the specified capacity.
40 | // If capacity is <= 0, it defaults to defaultCacheSize.
41 | func newDNSCache(capacity int) *dnsCache {
42 | if capacity <= 0 {
43 | capacity = defaultCacheSize
44 | }
45 |
46 | head := &cacheNode{}
47 | tail := &cacheNode{}
48 | head.next = tail
49 | tail.prev = head
50 |
51 | return &dnsCache{
52 | capacity: capacity,
53 | cache: make(map[string]*cacheNode),
54 | head: head,
55 | tail: tail,
56 | }
57 | }
58 |
59 | // get retrieves a cached DNS result by key.
60 | // It checks for expiration and updates the LRU order on cache hits.
61 | // Returns (result, found) where found indicates if the key was in cache and not expired.
62 | func (c *dnsCache) get(key string) (*Result, bool) {
63 | c.mutex.Lock()
64 | defer c.mutex.Unlock()
65 |
66 | node, exists := c.cache[key]
67 | if !exists {
68 | return nil, false
69 | }
70 |
71 | if time.Now().After(node.entry.expiry) {
72 | c.removeNode(node)
73 | delete(c.cache, key)
74 | return nil, false
75 | }
76 |
77 | node.entry.lastUsed = time.Now()
78 | c.moveToHead(node)
79 |
80 | return node.entry.result, true
81 | }
82 |
83 | // put stores a DNS result in the cache with the specified TTL.
84 | // This is a convenience wrapper around putWithNegative for positive cache entries.
85 | func (c *dnsCache) put(key string, result *Result, ttl time.Duration) {
86 | c.putWithNegative(key, result, ttl, false)
87 | }
88 |
89 | // putNegative stores a negative DNS result (like NXDOMAIN) in the cache.
90 | // Negative entries are handled specially for cache management purposes.
91 | func (c *dnsCache) putNegative(key string, result *Result, ttl time.Duration) {
92 | c.putWithNegative(key, result, ttl, true)
93 | }
94 |
95 | // putWithNegative is the internal implementation for storing cache entries.
96 | // It handles both positive and negative cache entries, manages LRU ordering,
97 | // and evicts old entries when the cache reaches capacity.
98 | func (c *dnsCache) putWithNegative(key string, result *Result, ttl time.Duration, negative bool) {
99 | c.mutex.Lock()
100 | defer c.mutex.Unlock()
101 |
102 | now := time.Now()
103 | entry := &cacheEntry{
104 | result: result,
105 | expiry: now.Add(ttl),
106 | lastUsed: now,
107 | negative: negative,
108 | }
109 |
110 | if node, exists := c.cache[key]; exists {
111 | node.entry = entry
112 | c.moveToHead(node)
113 | return
114 | }
115 |
116 | newNode := &cacheNode{
117 | key: key,
118 | entry: entry,
119 | }
120 |
121 | c.cache[key] = newNode
122 | c.addToHead(newNode)
123 |
124 | if len(c.cache) > c.capacity {
125 | tail := c.removeTail()
126 | delete(c.cache, tail.key)
127 | }
128 | }
129 |
130 | // addToHead adds a node to the head of the doubly-linked list (most recent position).
131 | func (c *dnsCache) addToHead(node *cacheNode) {
132 | node.prev = c.head
133 | node.next = c.head.next
134 | c.head.next.prev = node
135 | c.head.next = node
136 | }
137 |
138 | // removeNode removes a node from the doubly-linked list.
139 | func (c *dnsCache) removeNode(node *cacheNode) {
140 | node.prev.next = node.next
141 | node.next.prev = node.prev
142 | }
143 |
144 | // moveToHead moves an existing node to the head of the list (marks as most recently used).
145 | func (c *dnsCache) moveToHead(node *cacheNode) {
146 | c.removeNode(node)
147 | c.addToHead(node)
148 | }
149 |
150 | // removeTail removes and returns the node at the tail of the list (least recently used).
151 | func (c *dnsCache) removeTail() *cacheNode {
152 | lastNode := c.tail.prev
153 | c.removeNode(lastNode)
154 | return lastNode
155 | }
156 |
--------------------------------------------------------------------------------
/save/savezone.go:
--------------------------------------------------------------------------------
1 | // Package save provides functionality for writing DNS zone files to disk with compression.
2 | // It handles the creation, writing, and finalization of zone files, including
3 | // automatic gzip compression, metadata comments, and atomic file operations
4 | // to ensure data integrity during the zone transfer process.
5 | package save
6 |
7 | import (
8 | "bufio"
9 | "compress/gzip"
10 | "errors"
11 | "fmt"
12 | "os"
13 | "time"
14 |
15 | "github.com/miekg/dns"
16 | )
17 |
18 | // File represents a zone file being written to disk with compression.
19 | // It manages the lifecycle of creating, writing, and finalizing DNS zone files.
20 | type File struct {
21 | filename string // Final filename for the zone file
22 | filenameTmp string // Temporary filename during writing
23 | zone string // Zone name being written
24 | bufWriter *bufio.Writer // Buffered writer for performance
25 | gzWriter *gzip.Writer // Gzip compression writer
26 | fileWriter *os.File // Underlying file writer
27 | records int64 // Number of DNS records written
28 | closed bool // Whether the file has been finalized
29 | pendingWrites []string // Comments buffered until first record is added
30 | }
31 |
32 | // New creates a new zone file writer for the specified zone and filename.
33 | // The file is not created until the first record is written, allowing
34 | // comments to be buffered efficiently.
35 | func New(zone, filename string) *File {
36 | f := new(File)
37 | f.filename = filename
38 | f.filenameTmp = fmt.Sprintf("%s.tmp", f.filename)
39 | f.zone = zone
40 | return f
41 | }
42 |
43 | // Records returns the number of DNS records written to the zone file.
44 | func (f *File) Records() int64 {
45 | return f.records
46 | }
47 |
48 | // WriteComment adds a comment to the zone file
49 | func (f *File) WriteComment(comment string) error {
50 | if f.closed {
51 | return ErrFileClosed
52 | }
53 | // If file isn't created yet, buffer the comment
54 | if f.bufWriter == nil {
55 | f.pendingWrites = append(f.pendingWrites, fmt.Sprintf("; %s", comment))
56 | return nil
57 | }
58 | // File is already created, write directly
59 | _, err := fmt.Fprintf(f.bufWriter, "; %s", comment)
60 | return err
61 | }
62 |
63 | // WriteCommentKey writes a key-value comment pair to the zone file.
64 | // The comment is formatted as "; key: value\n".
65 | func (f *File) WriteCommentKey(key, value string) error {
66 | return f.WriteComment(fmt.Sprintf("%s: %s\n", key, value))
67 | }
68 |
69 | // ErrFileClosed is returned when attempting to write to a file that has been closed.
70 | var ErrFileClosed = errors.New("file is already closed")
71 |
72 | // fileReady ensures the file is created and ready for writing.
73 | // It creates the temporary file, sets up compression, and writes initial metadata.
74 | // This function is safe to call multiple times.
75 | func (f *File) fileReady() error {
76 | var err error
77 | if f.closed {
78 | return ErrFileClosed
79 | }
80 | if f.bufWriter == nil {
81 | f.fileWriter, err = os.Create(f.filenameTmp)
82 | if err != nil {
83 | return err
84 | }
85 | f.gzWriter = gzip.NewWriter(f.fileWriter)
86 | f.gzWriter.ModTime = time.Now()
87 | f.gzWriter.Name = fmt.Sprintf("%s.zone", f.zone[:len(f.zone)-1])
88 | f.bufWriter = bufio.NewWriter(f.gzWriter)
89 |
90 | // Write timestamp and zone metadata
91 | _, err = fmt.Fprintf(f.bufWriter, "; timestamp: %s\n", time.Now().Format(time.RFC3339))
92 | if err != nil {
93 | return err
94 | }
95 | _, err = fmt.Fprintf(f.bufWriter, "; zone: %s\n", f.zone)
96 | if err != nil {
97 | return err
98 | }
99 |
100 | // Write all buffered comments
101 | for _, comment := range f.pendingWrites {
102 | _, err = fmt.Fprintf(f.bufWriter, "%s", comment)
103 | if err != nil {
104 | return err
105 | }
106 | }
107 | // Clear the buffer
108 | f.pendingWrites = nil
109 | }
110 | return nil
111 | }
112 |
113 | // AddRR adds a record to a zone file
114 | func (f *File) AddRR(rr dns.RR) error {
115 | // create file here on first rr
116 | err := f.fileReady()
117 | if err != nil {
118 | return err
119 | }
120 |
121 | _, err = fmt.Fprintf(f.bufWriter, "%s\n", rr.String())
122 | if err != nil {
123 | return err
124 | }
125 | f.records++
126 | return nil
127 | }
128 |
129 | // Abort cancels the zone file creation and removes any temporary files.
130 | // It sets the record count to 0 to ensure the file is deleted rather than saved.
131 | func (f *File) Abort() error {
132 | f.records = 0 // forces finish to remove the file
133 | return f.Finish()
134 | }
135 |
136 | // Finish adds closing comments and flushes and closes all buffers/files
137 | func (f *File) Finish() error {
138 | if f.closed {
139 | return nil
140 | }
141 |
142 | // If no file was created (no records were added), just mark as closed
143 | if f.bufWriter == nil {
144 | f.closed = true
145 | return nil
146 | }
147 |
148 | // function to finish/close/safe the files when done
149 | if f.records > 1 {
150 | // save record count comment at end of zone file
151 | err := f.WriteCommentKey("records", fmt.Sprintf("%d", f.records))
152 | if err != nil {
153 | return err
154 | }
155 | }
156 | var err error
157 | if f.bufWriter != nil {
158 | err = f.bufWriter.Flush()
159 | if err != nil {
160 | return err
161 | }
162 | err = f.gzWriter.Flush()
163 | if err != nil {
164 | return err
165 | }
166 | err = f.gzWriter.Close()
167 | if err != nil {
168 | return err
169 | }
170 | err = f.fileWriter.Close()
171 | if err != nil {
172 | return err
173 | }
174 | }
175 | if f.records > 0 {
176 | err = os.Rename(f.filenameTmp, f.filename)
177 | } else {
178 | err = os.Remove(f.filenameTmp)
179 | }
180 | if err != nil {
181 | return err
182 | }
183 | f.closed = true
184 | return nil
185 | }
186 |
--------------------------------------------------------------------------------
/resolver/context_test.go:
--------------------------------------------------------------------------------
1 | package resolver
2 |
3 | import (
4 | "context"
5 | "testing"
6 | "time"
7 |
8 | "github.com/miekg/dns"
9 | )
10 |
11 | func TestResolverContextCancellation(t *testing.T) {
12 | resolver := New()
13 |
14 | t.Run("Resolve_CancelledContext", func(t *testing.T) {
15 | ctx, cancel := context.WithCancel(context.Background())
16 | cancel()
17 |
18 | _, err := resolver.Resolve(ctx, "google.com", dns.TypeA)
19 | if err == nil {
20 | t.Error("Expected error due to cancelled context, but got nil")
21 | }
22 | t.Logf("Got error (as expected): %v", err)
23 | })
24 |
25 | t.Run("ResolveAll_CancelledContext", func(t *testing.T) {
26 | ctx, cancel := context.WithCancel(context.Background())
27 | cancel()
28 |
29 | _, err := resolver.ResolveAll(ctx, "google.com", dns.TypeA)
30 | if err == nil {
31 | t.Error("Expected error due to cancelled context, but got nil")
32 | }
33 | t.Logf("Got error (as expected): %v", err)
34 | })
35 |
36 | t.Run("LookupIP_CancelledContext", func(t *testing.T) {
37 | ctx, cancel := context.WithCancel(context.Background())
38 | cancel()
39 |
40 | _, err := resolver.LookupIP(ctx, "google.com")
41 | if err == nil {
42 | t.Error("Expected error due to cancelled context, but got nil")
43 | }
44 | t.Logf("Got error (as expected): %v", err)
45 | })
46 |
47 | t.Run("LookupIPAll_CancelledContext", func(t *testing.T) {
48 | ctx, cancel := context.WithCancel(context.Background())
49 | cancel()
50 |
51 | _, err := resolver.LookupIPAll(ctx, "google.com")
52 | if err == nil {
53 | t.Error("Expected error due to cancelled context, but got nil")
54 | }
55 | t.Logf("Got error (as expected): %v", err)
56 | })
57 | }
58 |
59 | func TestResolverContextTimeout(t *testing.T) {
60 | resolver := New()
61 |
62 | t.Run("Resolve_ShortTimeout", func(t *testing.T) {
63 | ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
64 | defer cancel()
65 |
66 | _, err := resolver.Resolve(ctx, "google.com", dns.TypeA)
67 | if err == nil {
68 | t.Error("Expected error due to context timeout, but got nil")
69 | }
70 | t.Logf("Got error (as expected): %v", err)
71 | })
72 |
73 | t.Run("ResolveAll_ShortTimeout", func(t *testing.T) {
74 | ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
75 | defer cancel()
76 |
77 | _, err := resolver.ResolveAll(ctx, "google.com", dns.TypeA)
78 | if err == nil {
79 | t.Error("Expected error due to context timeout, but got nil")
80 | }
81 | t.Logf("Got error (as expected): %v", err)
82 | })
83 |
84 | t.Run("LookupIP_ShortTimeout", func(t *testing.T) {
85 | ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
86 | defer cancel()
87 |
88 | _, err := resolver.LookupIP(ctx, "google.com")
89 | if err == nil {
90 | t.Error("Expected error due to context timeout, but got nil")
91 | }
92 | t.Logf("Got error (as expected): %v", err)
93 | })
94 |
95 | t.Run("LookupIPAll_ShortTimeout", func(t *testing.T) {
96 | ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
97 | defer cancel()
98 |
99 | _, err := resolver.LookupIPAll(ctx, "google.com")
100 | if err == nil {
101 | t.Error("Expected error due to context timeout, but got nil")
102 | }
103 | t.Logf("Got error (as expected): %v", err)
104 | })
105 | }
106 |
107 | func TestResolverContextCancellationDuringQuery(t *testing.T) {
108 | resolver := NewWithTimeout(10 * time.Second)
109 |
110 | t.Run("CancelDuringResolve", func(t *testing.T) {
111 | ctx, cancel := context.WithCancel(context.Background())
112 |
113 | done := make(chan struct{})
114 | started := make(chan struct{})
115 | var err error
116 |
117 | go func() {
118 | defer close(done)
119 | close(started) // Signal that the goroutine has started
120 | // Use a domain that doesn't exist to force multiple recursive queries
121 | // This increases the chance of cancellation during resolution
122 | _, err = resolver.Resolve(ctx, "nonexistent.test.invalid", dns.TypeA)
123 | }()
124 |
125 | // Wait for the goroutine to actually start the query
126 | <-started
127 | // Add a small delay to let the query start, then cancel
128 | time.Sleep(10 * time.Millisecond)
129 | cancel()
130 |
131 | select {
132 | case <-done:
133 | // Test passes if either:
134 | // 1. Context was cancelled (err contains "context canceled")
135 | // 2. Query completed with NXDOMAIN or other DNS error
136 | // Both outcomes demonstrate the resolver handles context correctly
137 | t.Logf("Context cancellation handled: %v", err)
138 | case <-time.After(5 * time.Second):
139 | t.Error("Query did not complete within timeout after context cancellation")
140 | }
141 | })
142 |
143 | t.Run("CancelDuringResolveAll", func(t *testing.T) {
144 | ctx, cancel := context.WithCancel(context.Background())
145 |
146 | done := make(chan struct{})
147 | started := make(chan struct{})
148 | var err error
149 |
150 | go func() {
151 | defer close(done)
152 | close(started) // Signal that the goroutine has started
153 | // Use a domain that doesn't exist to force multiple recursive queries
154 | // This increases the chance of cancellation during resolution
155 | _, err = resolver.ResolveAll(ctx, "nonexistent.test.invalid", dns.TypeA)
156 | }()
157 |
158 | // Wait for the goroutine to actually start the query
159 | <-started
160 | // Add a small delay to let the query start, then cancel
161 | time.Sleep(10 * time.Millisecond)
162 | cancel()
163 |
164 | select {
165 | case <-done:
166 | // Test passes if either:
167 | // 1. Context was cancelled (err contains "context canceled")
168 | // 2. Query completed with NXDOMAIN or other DNS error
169 | // Both outcomes demonstrate the resolver handles context correctly
170 | t.Logf("Context cancellation handled: %v", err)
171 | case <-time.After(5 * time.Second):
172 | t.Error("Query did not complete within timeout after context cancellation")
173 | }
174 | })
175 | }
176 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | // Package main implements ALLXFR, a tool that performs DNS zone transfers (AXFR)
2 | // against root zone servers and attempts opportunistic zone transfers for every
3 | // nameserver IP to discover publicly available zone data.
4 | package main
5 |
6 | import (
7 | "context"
8 | "flag"
9 | "fmt"
10 | "log"
11 | "os"
12 | "strings"
13 | "time"
14 |
15 | "github.com/lanrat/allxfr/resolver"
16 | "github.com/lanrat/allxfr/status"
17 | "github.com/lanrat/allxfr/zone"
18 |
19 | "github.com/lanrat/allxfr/psl"
20 |
21 | "golang.org/x/sync/errgroup"
22 | )
23 |
24 | var (
25 | parallel = flag.Uint("parallel", 10, "number of parallel zone transfers to perform")
26 | saveDir = flag.String("out", "zones", "directory to save found zones in")
27 | verbose = flag.Bool("verbose", false, "enable verbose output")
28 | zonefile = flag.String("zonefile", "", "use the provided zonefile instead of getting the root zonefile")
29 | saveAll = flag.Bool("save-all", false, "attempt AXFR from every nameserver for a given zone and save all answers")
30 | usePSL = flag.Bool("psl", false, "attempt AXFR from zones listed in the public suffix list")
31 | ixfr = flag.Bool("ixfr", false, "attempt an IXFR instead of AXFR")
32 | dryRun = flag.Bool("dry-run", false, "only test if xfr is allowed by retrieving one envelope")
33 | retry = flag.Int("retry", 3, "number of times to retry failed operations")
34 | overwrite = flag.Bool("overwrite", false, "if zone already exists on disk, overwrite it with newer data")
35 | statusAddr = flag.String("status-listen", "", "enable HTTP status server on specified [IP:]port (e.g., '8080', '127.0.0.1:8080', '[::1]:8080')")
36 | showVersion = flag.Bool("version", false, "print version and exit") // Show version
37 |
38 | )
39 |
40 | var (
41 | version = "dev" // Version string, set at build time
42 | totalXFR uint32
43 | resolve *resolver.Resolver
44 | statusServer *status.StatusServer
45 | )
46 |
47 | const (
48 | globalTimeout = 15 * time.Second
49 | )
50 |
51 | // main is the entry point for the ALLXFR application.
52 | // It parses command-line flags, initializes the resolver and status server,
53 | // obtains zone data (from root AXFR, zonefile, or PSL), and orchestrates
54 | // parallel zone transfer attempts across all discovered nameservers.
55 | func main() {
56 | flag.Parse()
57 | if *showVersion {
58 | fmt.Println(version)
59 | return
60 | }
61 | if *retry < 1 {
62 | log.Fatal("retry must be positive")
63 | }
64 |
65 | // Start HTTP status server if address is specified
66 | if *statusAddr != "" {
67 | statusServer = status.StartStatusServer(*statusAddr)
68 | }
69 |
70 | resolve = resolver.New()
71 | start := time.Now()
72 | var z zone.Zone
73 | var err error
74 |
75 | if len(*zonefile) > 1 {
76 | // zone file is provided
77 | v("parsing zonefile: %q\n", *zonefile)
78 | z, err = zone.ParseZoneFile(*zonefile)
79 | check(err)
80 | } else if len(*zonefile) == 0 && flag.NArg() == 0 {
81 | // get zone file from root AXFR
82 | // not all the root nameservers allow AXFR, try them until we find one that does
83 | for _, ns := range resolver.RootServerNames {
84 | v("trying root nameserver %s", ns)
85 | startTime := time.Now()
86 | z, err = zone.RootAXFR(ns)
87 | if err == nil {
88 | took := time.Since(startTime).Round(time.Millisecond)
89 | log.Printf("ROOT %s xfr size: %d records in %s \n", ns, z.Records, took.String())
90 | break
91 | }
92 | }
93 | }
94 |
95 | if flag.NArg() > 0 {
96 | for _, domain := range flag.Args() {
97 | z.AddNS(domain, "")
98 | }
99 | }
100 |
101 | if z.CountNS() == 0 {
102 | log.Fatal("Got empty zone")
103 | }
104 |
105 | if *usePSL {
106 | pslDomains, err := psl.GetDomains()
107 | check(err)
108 | for _, domain := range pslDomains {
109 | z.AddNS(domain, "")
110 | }
111 | v("added %d domains from PSL\n", len(pslDomains))
112 | }
113 |
114 | if statusServer != nil {
115 | statusServer.IncrementTotalZones(uint32(z.CountNS()))
116 | }
117 |
118 | // create output dir if does not exist
119 | if !*dryRun {
120 | if _, err := os.Stat(*saveDir); os.IsNotExist(err) {
121 | err = os.MkdirAll(*saveDir, os.ModePerm)
122 | check(err)
123 | }
124 | }
125 |
126 | if *verbose {
127 | z.PrintTree()
128 | }
129 |
130 | ctx := context.Background()
131 |
132 | zoneChan := z.GetNameChan()
133 | var g errgroup.Group
134 |
135 | // start workers
136 | for i := uint(0); i < *parallel; i++ {
137 | g.Go(func() error { return worker(ctx, z, zoneChan) })
138 | }
139 |
140 | err = g.Wait()
141 | check(err)
142 | took := time.Since(start).Round(time.Millisecond)
143 | log.Printf("%d / %d transferred in %s\n", totalXFR, len(z.NS), took.String())
144 | v("exiting normally\n")
145 | }
146 |
147 | // worker processes domains from the channel and attempts zone transfers.
148 | // It receives domain names from the channel and calls axfrWorker to attempt
149 | // zone transfers for each domain. Updates the status server with transfer progress.
150 | func worker(ctx context.Context, z zone.Zone, c chan string) error {
151 | for {
152 | domain, more := <-c
153 | if !more {
154 | return nil
155 | }
156 |
157 | // Update status server with new domain discovered
158 | if statusServer != nil {
159 | statusServer.StartTransfer(domain)
160 | }
161 |
162 | err := axfrWorker(ctx, z, domain)
163 | if err != nil {
164 | if statusServer != nil {
165 | statusServer.FailTransfer(domain, err.Error())
166 | }
167 | continue
168 | }
169 |
170 | // If no error occurred, the domain processing is complete
171 | // Success/failure status is handled within axfr function based on actual transfers
172 | }
173 | }
174 |
175 | // check is a utility function that terminates the program with log.Fatal
176 | // if the provided error is not nil. Used for handling critical errors.
177 | func check(err error) {
178 | if err != nil {
179 | log.Fatal(err)
180 | }
181 | }
182 |
183 | // v prints verbose output if the verbose flag is enabled.
184 | // It formats the message and prefixes each line with a tab for indentation.
185 | func v(format string, v ...interface{}) {
186 | if *verbose {
187 | line := fmt.Sprintf(format, v...)
188 | lines := strings.ReplaceAll(line, "\n", "\n\t")
189 | log.Print(lines)
190 | }
191 | }
192 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | cloud.google.com/go/compute/metadata v0.2.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
2 | github.com/ProtonMail/go-crypto v0.0.0-20230217124315-7d5c6f04bbb8/go.mod h1:I0gYDMZ6Z5GRU7l58bNFSkPTFN6Yl12dsUlAZ8xy98g=
3 | github.com/bwesterb/go-ristretto v1.2.0/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
4 | github.com/cloudflare/circl v1.1.0/go.mod h1:prBCrKB9DV4poKZY1l9zBXg2QJY7mvgRvtMxxK7fi4I=
5 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
6 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
7 | github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
8 | github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
9 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
10 | github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
11 | github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
12 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
13 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
14 | github.com/google/go-github/v50 v50.2.0/go.mod h1:VBY8FB6yPIjrtKhozXv4FQupxKLS6H4m6xFZlT43q8Q=
15 | github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
16 | github.com/miekg/dns v1.1.67 h1:kg0EHj0G4bfT5/oOys6HhZw4vmMlnoZ+gDu8tJ/AlI0=
17 | github.com/miekg/dns v1.1.67/go.mod h1:fujopn7TB3Pu3JM69XaawiU0wqjpL9/8xGop5UrTPps=
18 | github.com/weppos/publicsuffix-go v0.40.2 h1:LlnoSH0Eqbsi3ReXZWBKCK5lHyzf3sc1JEHH1cnlfho=
19 | github.com/weppos/publicsuffix-go v0.40.2/go.mod h1:XsLZnULC3EJ1Gvk9GVjuCTZ8QUu9ufE4TZpOizDShko=
20 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
21 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
22 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
23 | golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
24 | golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
25 | golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
26 | golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
27 | golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
28 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
29 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
30 | golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
31 | golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
32 | golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
33 | golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
34 | golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
35 | golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
36 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
37 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
38 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
39 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
40 | golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
41 | golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
42 | golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
43 | golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
44 | golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
45 | golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE=
46 | golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
47 | golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
48 | golang.org/x/oauth2 v0.6.0/go.mod h1:ycmewcwgD4Rpr3eZJLSB4Kyyljb3qDh40vJ8STE5HKw=
49 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
50 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
51 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
52 | golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
53 | golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
54 | golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
55 | golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
56 | golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
57 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
58 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
59 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
60 | golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
61 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
62 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
63 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
64 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
65 | golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
66 | golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
67 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
68 | golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
69 | golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
70 | golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
71 | golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
72 | golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
73 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
74 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
75 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
76 | golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
77 | golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
78 | golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
79 | golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
80 | golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
81 | golang.org/x/term v0.22.0/go.mod h1:F3qCibpT5AMpCRfhfT53vVJwhLtIVHhB9XDjfFvnMI4=
82 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
83 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
84 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
85 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
86 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
87 | golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
88 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
89 | golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
90 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
91 | golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
92 | golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
93 | golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
94 | golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
95 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
96 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
97 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
98 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
99 | golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
100 | golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
101 | golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
102 | golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
103 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
104 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
105 | google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
106 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
107 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
108 | google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
109 | google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
110 |
--------------------------------------------------------------------------------
/status/status.go:
--------------------------------------------------------------------------------
1 | // Package status provides HTTP endpoints and tracking for DNS zone transfer operations.
2 | // It maintains real-time statistics about transfer progress, success/failure rates,
3 | // and active transfers, while also providing a cleanup mechanism to prevent memory
4 | // leaks from stale transfer entries. The package exposes JSON APIs for monitoring
5 | // the ALLXFR application's performance and progress.
6 | package status
7 |
8 | import (
9 | "encoding/json"
10 | "log"
11 | "math"
12 | "net"
13 | "net/http"
14 | "strings"
15 | "sync"
16 | "sync/atomic"
17 | "time"
18 | )
19 |
20 | // StatusServer tracks the status of zone transfers and provides HTTP endpoints
21 | type StatusServer struct {
22 | startTime time.Time
23 | totalZones uint32
24 | completed uint32
25 | failed uint32
26 | active sync.Map // map[string]time.Time - active zone transfers
27 | activeCount uint32
28 | mu sync.RWMutex
29 | recentFailed []string // recent failures for debugging
30 | }
31 |
32 | // StatusResponse represents the JSON response for status endpoint
33 | type StatusResponse struct {
34 | StartTime time.Time `json:"start_time"`
35 | Runtime string `json:"runtime"`
36 | TotalZones uint32 `json:"total_zones"`
37 | Completed uint32 `json:"completed"`
38 | Failed uint32 `json:"failed"`
39 | Active uint32 `json:"active"`
40 | Remaining uint32 `json:"remaining"`
41 | SuccessRate float64 `json:"success_rate"`
42 | TransferRate float64 `json:"transfer_rate_per_minute"`
43 | RecentFailed []string `json:"recent_failed,omitempty"`
44 | ActiveZones []string `json:"active_zones,omitempty"`
45 | }
46 |
47 | // HealthResponse represents the JSON response for health endpoint
48 | type HealthResponse struct {
49 | Status string `json:"status"`
50 | Message string `json:"message"`
51 | }
52 |
53 | // NewStatusServer creates a new status server instance
54 | func NewStatusServer() *StatusServer {
55 | s := &StatusServer{
56 | startTime: time.Now(),
57 | totalZones: 0, // Will be updated as domains are discovered
58 | recentFailed: make([]string, 0),
59 | }
60 |
61 | // Start cleanup goroutine to prevent memory leaks from stale active entries
62 | go s.cleanupStaleEntries()
63 |
64 | return s
65 | }
66 |
67 | // IncrementTotalZones increments the total zone count as domains are discovered
68 | func (s *StatusServer) IncrementTotalZones(change uint32) {
69 | atomic.AddUint32(&s.totalZones, change)
70 | }
71 |
72 | // StartTransfer marks a zone as actively being transferred
73 | func (s *StatusServer) StartTransfer(zone string) {
74 | s.active.Store(zone, time.Now())
75 | atomic.AddUint32(&s.activeCount, 1)
76 | }
77 |
78 | // CompleteTransfer marks a zone transfer as completed
79 | func (s *StatusServer) CompleteTransfer(zone string) {
80 | // Only process if the zone is still active (avoid double-counting)
81 | if _, exists := s.active.LoadAndDelete(zone); exists {
82 | atomic.AddUint32(&s.activeCount, ^uint32(0)) // decrement
83 | atomic.AddUint32(&s.completed, 1)
84 | }
85 | }
86 |
87 | // FailTransfer marks a zone transfer as failed
88 | func (s *StatusServer) FailTransfer(zone string, reason string) {
89 | // Only process if the zone is still active (avoid double-counting)
90 | if _, exists := s.active.LoadAndDelete(zone); exists {
91 | atomic.AddUint32(&s.activeCount, ^uint32(0)) // decrement
92 | atomic.AddUint32(&s.failed, 1)
93 |
94 | // Add to recent failures (keep last 10)
95 | s.mu.Lock()
96 | failureEntry := zone
97 | if reason != "" {
98 | failureEntry += ": " + reason
99 | }
100 | s.recentFailed = append(s.recentFailed, failureEntry)
101 | if len(s.recentFailed) > 10 {
102 | s.recentFailed = s.recentFailed[1:]
103 | }
104 | s.mu.Unlock()
105 | }
106 | }
107 |
108 | // GetStatus returns current status information
109 | func (s *StatusServer) GetStatus() StatusResponse {
110 | s.mu.RLock()
111 | recentFailed := make([]string, len(s.recentFailed))
112 | copy(recentFailed, s.recentFailed)
113 | s.mu.RUnlock()
114 |
115 | completed := atomic.LoadUint32(&s.completed)
116 | failed := atomic.LoadUint32(&s.failed)
117 | active := atomic.LoadUint32(&s.activeCount)
118 | totalZones := atomic.LoadUint32(&s.totalZones)
119 |
120 | // Collect active zone names
121 | var activeZones []string
122 | s.active.Range(func(key, value interface{}) bool {
123 | if zone, ok := key.(string); ok {
124 | activeZones = append(activeZones, zone)
125 | }
126 | return true // continue iteration
127 | })
128 |
129 | runtime := time.Since(s.startTime)
130 | remaining := uint32(0)
131 | if totalZones > completed+failed {
132 | remaining = totalZones - completed - failed
133 | }
134 |
135 | var successRate float64
136 | if completed+failed > 0 {
137 | successRate = math.Round(float64(completed)/float64(completed+failed)*100*100) / 100
138 | }
139 |
140 | var transferRate float64
141 | if runtime.Minutes() > 0 {
142 | transferRate = math.Round(float64(completed)/runtime.Minutes()*100) / 100
143 | }
144 |
145 | return StatusResponse{
146 | StartTime: s.startTime,
147 | Runtime: runtime.Round(time.Second).String(),
148 | TotalZones: totalZones,
149 | Completed: completed,
150 | Failed: failed,
151 | Active: active,
152 | Remaining: remaining,
153 | SuccessRate: successRate,
154 | TransferRate: transferRate,
155 | RecentFailed: recentFailed,
156 | ActiveZones: activeZones,
157 | }
158 | }
159 |
160 | // cleanupStaleEntries periodically removes entries from the active map that have been
161 | // active for too long (likely due to missed FailTransfer/CompleteTransfer calls)
162 | func (s *StatusServer) cleanupStaleEntries() {
163 | ticker := time.NewTicker(5 * time.Minute)
164 | defer ticker.Stop()
165 |
166 | for range ticker.C {
167 | now := time.Now()
168 | staleThreshold := 10 * time.Minute // Consider entries stale after 10 minutes
169 |
170 | s.active.Range(func(key, value interface{}) bool {
171 | if startTime, ok := value.(time.Time); ok {
172 | if now.Sub(startTime) > staleThreshold {
173 | // Remove stale entry and count it as failed
174 | if _, exists := s.active.LoadAndDelete(key); exists {
175 | atomic.AddUint32(&s.activeCount, ^uint32(0)) // decrement
176 | atomic.AddUint32(&s.failed, 1)
177 |
178 | s.mu.Lock()
179 | zone := key.(string)
180 | failureEntry := zone + ": stale transfer (cleanup)"
181 | s.recentFailed = append(s.recentFailed, failureEntry)
182 | if len(s.recentFailed) > 10 {
183 | s.recentFailed = s.recentFailed[1:]
184 | }
185 | s.mu.Unlock()
186 | }
187 | }
188 | }
189 | return true // continue iteration
190 | })
191 | }
192 | }
193 |
194 | // HTTP Handlers
195 |
196 | func (s *StatusServer) statusHandler(w http.ResponseWriter, r *http.Request) {
197 | if s == nil {
198 | http.Error(w, "Status server not initialized", http.StatusInternalServerError)
199 | return
200 | }
201 |
202 | status := s.GetStatus()
203 | w.Header().Set("Content-Type", "application/json")
204 | if err := json.NewEncoder(w).Encode(status); err != nil {
205 | http.Error(w, "Failed to encode status", http.StatusInternalServerError)
206 | return
207 | }
208 | }
209 |
210 | func (s *StatusServer) healthHandler(w http.ResponseWriter, r *http.Request) {
211 | health := HealthResponse{
212 | Status: "ok",
213 | Message: "ALLXFR is running",
214 | }
215 |
216 | w.Header().Set("Content-Type", "application/json")
217 | if err := json.NewEncoder(w).Encode(health); err != nil {
218 | http.Error(w, "Failed to encode health response", http.StatusInternalServerError)
219 | return
220 | }
221 | }
222 |
223 | func (s *StatusServer) progressHandler(w http.ResponseWriter, r *http.Request) {
224 | if s == nil {
225 | http.Error(w, "Status server not initialized", http.StatusInternalServerError)
226 | return
227 | }
228 |
229 | status := s.GetStatus()
230 |
231 | // Simplified progress response
232 | attempted := status.Completed + status.Failed
233 | var percentage float64
234 | if status.TotalZones > 0 {
235 | percentage = math.Round(float64(attempted)/float64(status.TotalZones)*100*100) / 100
236 | }
237 |
238 | progress := map[string]interface{}{
239 | "completed": status.Completed,
240 | "failed": status.Failed,
241 | "attempted": attempted,
242 | "total": status.TotalZones,
243 | "remaining": status.Remaining,
244 | "active": status.Active,
245 | "percentage": percentage,
246 | }
247 |
248 | w.Header().Set("Content-Type", "application/json")
249 | if err := json.NewEncoder(w).Encode(progress); err != nil {
250 | http.Error(w, "Failed to encode progress response", http.StatusInternalServerError)
251 | return
252 | }
253 | }
254 |
255 | // StartStatusServer starts the HTTP status server in a separate goroutine
256 | func StartStatusServer(addr string) *StatusServer {
257 | statusServer := NewStatusServer()
258 |
259 | mux := http.NewServeMux()
260 | mux.HandleFunc("/status", statusServer.statusHandler)
261 | mux.HandleFunc("/health", statusServer.healthHandler)
262 | mux.HandleFunc("/progress", statusServer.progressHandler)
263 |
264 | // Parse address to handle both "port" and "ip:port" formats
265 | var serverAddr string
266 | if strings.Contains(addr, ":") {
267 | // Already in host:port format
268 | serverAddr = addr
269 | } else {
270 | // Just port, bind to all interfaces
271 | serverAddr = ":" + addr
272 | }
273 |
274 | server := &http.Server{
275 | Addr: serverAddr,
276 | Handler: mux,
277 | }
278 |
279 | go func() {
280 | host, port, err := net.SplitHostPort(serverAddr)
281 | if err != nil {
282 | log.Printf("Status server starting on %s", serverAddr)
283 | } else {
284 | if host == "" {
285 | host = "localhost"
286 | }
287 | log.Printf("Status server starting on %s", serverAddr)
288 | log.Printf("Available endpoints:")
289 | log.Printf(" http://%s:%s/status - Full status information", host, port)
290 | log.Printf(" http://%s:%s/progress - Progress summary", host, port)
291 | log.Printf(" http://%s:%s/health - Health check", host, port)
292 | }
293 |
294 | if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
295 | log.Printf("Status server error: %v", err)
296 | }
297 | }()
298 | return statusServer
299 | }
300 |
--------------------------------------------------------------------------------
/axfr.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "errors"
6 | "fmt"
7 | "log"
8 | "net"
9 | "os"
10 | "path"
11 | "sync/atomic"
12 | "time"
13 |
14 | "github.com/lanrat/allxfr/save"
15 | "github.com/lanrat/allxfr/zone"
16 |
17 | "github.com/miekg/dns"
18 | )
19 |
20 | // ErrAxfrUnsupported indicates that the nameserver does not support AXFR requests.
21 | // This is a common response when zone transfers are disabled on the server.
22 | var ErrAxfrUnsupported = errors.New("AXFR Unsupported")
23 |
24 | // ErrorAxfrUnsupportedWrap wraps DNS errors with ErrAxfrUnsupported when
25 | // the error indicates that AXFR is refused or not authorized.
26 | // It specifically handles DNS response codes 5 (Refused) and 9 (Not Authorized).
27 | func ErrorAxfrUnsupportedWrap(err error) error {
28 | if err == nil {
29 | return nil
30 | }
31 | errStr := err.Error()
32 | // "bad xfr rcode: 5" - Refused
33 | if errStr == "dns: bad xfr rcode: 5" {
34 | err = fmt.Errorf("%w 'Refused': %w", ErrAxfrUnsupported, err)
35 | }
36 | //"bad xfr rcode: 9" - Not Authorized / Not Authenticated
37 | if errStr == "dns: bad xfr rcode: 9" {
38 | err = fmt.Errorf("%w 'Not Authorized': %w", ErrAxfrUnsupported, err)
39 | }
40 | return err
41 | }
42 |
43 | // axfrWorker attempts zone transfers for a domain using all available nameservers and IPs.
44 | // It tries both glue records from the zone data and performs additional NS queries
45 | // to discover non-glue nameserver IPs. Returns nil if any transfer succeeds.
46 | func axfrWorker(ctx context.Context, z zone.Zone, domain string) error {
47 | attemptedIPs := make(map[string]bool)
48 | domain = dns.Fqdn(domain)
49 | var err error
50 | //var records int64
51 | var anySuccess bool
52 | for _, nameserver := range z.NS[domain] {
53 | // Check for context cancellation
54 | select {
55 | case <-ctx.Done():
56 | return ctx.Err()
57 | default:
58 | }
59 | for _, ip := range z.IP[nameserver] {
60 | ipString := ip.To16().String()
61 | if !attemptedIPs[ipString] {
62 | attemptedIPs[ipString] = true
63 | anySuccess, err = axfrRetry(ctx, ip, domain, nameserver)
64 | if err != nil {
65 | continue
66 | }
67 | if anySuccess {
68 | // got the zone
69 | return nil
70 | }
71 | }
72 | }
73 | }
74 |
75 | // query NS and run axfr on missing IPs
76 | var qNameservers []string
77 | for try := 0; try < *retry; try++ {
78 | result, err := resolve.Resolve(ctx, domain, dns.TypeNS)
79 | if err != nil {
80 | v("[%s] %s", domain, err)
81 | } else {
82 | for _, rr := range result.Answer {
83 | if ns, ok := rr.(*dns.NS); ok {
84 | qNameservers = append(qNameservers, ns.Ns)
85 | }
86 | }
87 | break
88 | }
89 | select {
90 | case <-ctx.Done():
91 | return ctx.Err()
92 | case <-time.After(1 * time.Second):
93 | }
94 | }
95 |
96 | for _, nameserver := range qNameservers {
97 | // Check for context cancellation
98 | select {
99 | case <-ctx.Done():
100 | return ctx.Err()
101 | default:
102 | }
103 | var qIPs []net.IP
104 | for try := 0; try < *retry; try++ {
105 | qIPs, err = resolve.LookupIPAll(ctx, nameserver)
106 | if err != nil {
107 | v("[%s] %s", domain, err)
108 | } else {
109 | break
110 | }
111 | select {
112 | case <-ctx.Done():
113 | return ctx.Err()
114 | case <-time.After(1 * time.Second):
115 | }
116 | }
117 |
118 | for _, ip := range qIPs {
119 | // Check for context cancellation
120 | select {
121 | case <-ctx.Done():
122 | return ctx.Err()
123 | default:
124 | }
125 | ipString := ip.To16().String()
126 | if !attemptedIPs[ipString] {
127 | attemptedIPs[ipString] = true
128 | v("[%s] trying non-glue AXFR: %s %s", domain, nameserver, ip.String())
129 | anySuccess, err = axfrRetry(ctx, ip, domain, nameserver)
130 | if err != nil {
131 | continue
132 | }
133 | if anySuccess {
134 | // got the zone
135 | return nil
136 | }
137 | }
138 | }
139 | }
140 |
141 | // If no successful transfers occurred, mark domain as failed
142 | if !anySuccess && statusServer != nil {
143 | statusServer.FailTransfer(domain, "no successful zone transfers")
144 | }
145 |
146 | return nil
147 | }
148 |
149 | // axfrRetry attempts a zone transfer with retry logic.
150 | // It retries failed transfers up to the configured retry count, but skips
151 | // retries if the nameserver explicitly doesn't support AXFR.
152 | // Returns (success, error) where success indicates if any records were transferred.
153 | func axfrRetry(ctx context.Context, ip net.IP, domain, nameserver string) (bool, error) {
154 | var err error
155 | var records int64
156 | var anySuccess bool
157 |
158 | for try := 0; try < *retry; try++ {
159 | records, err = axfr(ctx, domain, nameserver, ip)
160 | if err != nil {
161 | v("[%s] %s", domain, err)
162 | // if axfr is unsupported by NS, then move on, otherwise retry
163 | if errors.Is(err, ErrAxfrUnsupported) {
164 | err = nil
165 | // skip remaining tries with this IP
166 | break
167 | }
168 | } else {
169 | if records != 0 {
170 | anySuccess = true
171 | break
172 | }
173 | }
174 | select {
175 | case <-ctx.Done():
176 | return anySuccess, ctx.Err()
177 | case <-time.After(1 * time.Second):
178 | }
179 | }
180 | if !*saveAll && records != 0 {
181 | return anySuccess, nil
182 | }
183 | if err != nil {
184 | return anySuccess, err
185 | }
186 |
187 | return anySuccess, err
188 | }
189 |
190 | // axfr performs a single zone transfer attempt and logs the result.
191 | // It calls axfrToFile to perform the actual transfer and updates global
192 | // transfer statistics and status server on success.
193 | // Returns the number of records transferred.
194 | func axfr(ctx context.Context, domain, nameserver string, ip net.IP) (int64, error) {
195 | startTime := time.Now()
196 | records, err := axfrToFile(ctx, domain, ip, nameserver)
197 | if err == nil && records > 0 {
198 | took := time.Since(startTime).Round(time.Millisecond)
199 | log.Printf("[%s] %s (%s) xfr size: %d records in %s\n", domain, nameserver, ip.String(), records, took.String())
200 | atomic.AddUint32(&totalXFR, 1)
201 |
202 | // Update status server on successful transfer
203 | if statusServer != nil {
204 | statusServer.CompleteTransfer(domain)
205 | }
206 | }
207 | return records, err
208 | }
209 |
210 | // InContext performs a DNS zone transfer using the provided context and connection address.
211 | // It creates a TCP connection with context support and returns a channel of DNS envelopes
212 | // containing the transferred zone records. The transfer respects the context's cancellation
213 | // and uses global timeout settings for the connection operations.
214 | // It wraps miekg/dns.Transfer.In() with a Context
215 | func InContext(ctx context.Context, q *dns.Msg, a string) (env chan *dns.Envelope, err error) {
216 | // Create a dialer with context
217 | dialer := &net.Dialer{
218 | Timeout: globalTimeout,
219 | }
220 |
221 | // Dial with context
222 | conn, err := dialer.DialContext(ctx, "tcp", a)
223 | if err != nil {
224 | return nil, err
225 | }
226 |
227 | // Create DNS connection wrapper
228 | dnsConn := &dns.Conn{Conn: conn}
229 |
230 | // Create transfer with pre-configured connection
231 | transfer := &dns.Transfer{
232 | Conn: dnsConn,
233 | DialTimeout: globalTimeout,
234 | ReadTimeout: globalTimeout,
235 | WriteTimeout: globalTimeout,
236 | }
237 | return transfer.In(q, a)
238 | }
239 |
240 | // axfrToFile performs an AXFR or IXFR request and saves the results to a compressed file.
241 | // It handles file creation, DNS transfer setup with timeouts, and processes each
242 | // envelope of records. Returns the number of records transferred or -1 if the file
243 | // already exists and overwrite is disabled.
244 | func axfrToFile(ctx context.Context, zone string, ip net.IP, nameserver string) (int64, error) {
245 | zone = dns.Fqdn(zone)
246 |
247 | m := new(dns.Msg)
248 | if *ixfr {
249 | m.SetIxfr(zone, 0, "", "")
250 | } else {
251 | m.SetQuestion(zone, dns.TypeAXFR)
252 | }
253 |
254 | env, err := InContext(ctx, m, net.JoinHostPort(ip.String(), "53"))
255 | if err != nil {
256 | // skip on this error
257 | err = fmt.Errorf("transfer error from zone: %s ip: %s: %w", zone, ip.String(), err)
258 | v("[%s] %s", zone, err)
259 | return 0, nil
260 | }
261 |
262 | // get ready to save file
263 | var filename string
264 | if *saveAll {
265 | filename = path.Join(*saveDir, fmt.Sprintf("%s_%s_%s_zone.gz", zone, nameserver, ip.String()))
266 | } else {
267 | filename = path.Join(*saveDir, fmt.Sprintf("%s.zone.gz", zone[:len(zone)-1]))
268 | }
269 | if !*overwrite {
270 | if _, err := os.Stat(filename); err == nil || !os.IsNotExist(err) {
271 | v("[%s] file %q exists, skipping", zone, filename)
272 | return -1, nil
273 | }
274 | }
275 |
276 | var envelope int64
277 | zonefile := save.New(zone, filename)
278 | defer func() {
279 | err = zonefile.WriteCommentKey("envelopes", fmt.Sprintf("%d", envelope))
280 | if err != nil {
281 | panic(err)
282 | }
283 | err := zonefile.Finish()
284 | if err != nil {
285 | panic(err)
286 | }
287 | }()
288 | err = zonefile.WriteComment("Generated by ALLXFR (https://github.com/lanrat/allxfr)\n")
289 | if err != nil {
290 | return zonefile.Records(), err
291 | }
292 | err = zonefile.WriteCommentKey("nameserver", nameserver)
293 | if err != nil {
294 | return zonefile.Records(), err
295 | }
296 | err = zonefile.WriteCommentKey("nameserverIP", ip.String())
297 | if err != nil {
298 | return zonefile.Records(), err
299 | }
300 | axfrType := "AXFR"
301 | if *ixfr {
302 | axfrType = "IXFR"
303 | }
304 | err = zonefile.WriteCommentKey("xfr", axfrType)
305 | if err != nil {
306 | return zonefile.Records(), err
307 | }
308 |
309 | for e := range env {
310 | // Check for context cancellation
311 | select {
312 | case <-ctx.Done():
313 | return zonefile.Records(), ctx.Err()
314 | default:
315 | }
316 | if e.Error != nil {
317 | err = ErrorAxfrUnsupportedWrap(e.Error)
318 | // skip on this error
319 | err = fmt.Errorf("transfer envelope error from zone: %s ip: %s (rec: %d, envelope: %d): %w", zone, ip.String(), zonefile.Records(), envelope, err)
320 | return zonefile.Records(), err
321 | }
322 | // zonefile will not write anything to disk unless it has been provided records to write.
323 | if *dryRun && len(e.RR) > 0 {
324 | return int64(len(e.RR)), nil
325 | }
326 | for _, rr := range e.RR {
327 | // create file here on first iteration of loop
328 | err := zonefile.AddRR(rr)
329 | if err != nil {
330 | return zonefile.Records(), err
331 | }
332 | }
333 | envelope++
334 | }
335 |
336 | return zonefile.Records(), err
337 | }
338 |
--------------------------------------------------------------------------------
/resolver/resolver_test.go:
--------------------------------------------------------------------------------
1 | package resolver
2 |
3 | import (
4 | "context"
5 | "net"
6 | "sort"
7 | "testing"
8 |
9 | "github.com/miekg/dns"
10 | )
11 |
12 | func TestResolverA(t *testing.T) {
13 | resolver := New()
14 | testDomains := []string{
15 | "google.com",
16 | "github.com",
17 | "cloudflare.com",
18 | }
19 |
20 | ctx := context.Background()
21 |
22 | for _, domain := range testDomains {
23 | t.Run(domain, func(t *testing.T) {
24 | result, err := resolver.Resolve(ctx, domain, dns.TypeA)
25 | if err != nil {
26 | t.Fatalf("Failed to resolve %s: %v", domain, err)
27 | }
28 |
29 | if len(result.Answer) == 0 {
30 | t.Fatalf("No A records found for %s", domain)
31 | }
32 |
33 | var resolverIPs []net.IP
34 | for _, rr := range result.Answer {
35 | if a, ok := rr.(*dns.A); ok {
36 | resolverIPs = append(resolverIPs, a.A)
37 | }
38 | }
39 |
40 | if len(resolverIPs) == 0 {
41 | t.Fatalf("No A records in answer section for %s", domain)
42 | }
43 |
44 | systemIPs, err := net.LookupIP(domain)
45 | if err != nil {
46 | t.Fatalf("System lookup failed for %s: %v", domain, err)
47 | }
48 |
49 | var systemIPv4 []net.IP
50 | for _, ip := range systemIPs {
51 | if ip.To4() != nil {
52 | systemIPv4 = append(systemIPv4, ip)
53 | }
54 | }
55 |
56 | if len(systemIPv4) == 0 {
57 | t.Skipf("No IPv4 addresses from system resolver for %s", domain)
58 | }
59 |
60 | if !compareIPSets(resolverIPs, systemIPv4) {
61 | t.Logf("Resolver IPs: %v", resolverIPs)
62 | t.Logf("System IPs: %v", systemIPv4)
63 | t.Logf("Note: IP sets differ - this may be due to different DNS servers or timing")
64 | }
65 | })
66 | }
67 | }
68 |
69 | func TestResolverAAAA(t *testing.T) {
70 | resolver := New()
71 | testDomains := []string{
72 | "google.com",
73 | "github.com",
74 | "cloudflare.com",
75 | }
76 |
77 | ctx := context.Background()
78 |
79 | for _, domain := range testDomains {
80 | t.Run(domain, func(t *testing.T) {
81 | result, err := resolver.Resolve(ctx, domain, dns.TypeAAAA)
82 | if err != nil {
83 | t.Logf("No AAAA records for %s: %v", domain, err)
84 | return
85 | }
86 |
87 | var resolverIPs []net.IP
88 | for _, rr := range result.Answer {
89 | if aaaa, ok := rr.(*dns.AAAA); ok {
90 | resolverIPs = append(resolverIPs, aaaa.AAAA)
91 | }
92 | }
93 |
94 | systemIPs, err := net.LookupIP(domain)
95 | if err != nil {
96 | t.Fatalf("System lookup failed for %s: %v", domain, err)
97 | }
98 |
99 | var systemIPv6 []net.IP
100 | for _, ip := range systemIPs {
101 | if ip.To4() == nil && ip.To16() != nil {
102 | systemIPv6 = append(systemIPv6, ip)
103 | }
104 | }
105 |
106 | if len(resolverIPs) == 0 && len(systemIPv6) == 0 {
107 | t.Logf("No AAAA records for %s (expected)", domain)
108 | return
109 | }
110 |
111 | if len(resolverIPs) > 0 && len(systemIPv6) > 0 {
112 | if !compareIPSets(resolverIPs, systemIPv6) {
113 | t.Logf("Resolver IPv6: %v", resolverIPs)
114 | t.Logf("System IPv6: %v", systemIPv6)
115 | t.Logf("Note: IPv6 sets differ - this may be due to different DNS servers or timing")
116 | }
117 | }
118 | })
119 | }
120 | }
121 |
122 | func TestResolverNS(t *testing.T) {
123 | resolver := New()
124 | testDomains := []string{
125 | "google.com",
126 | "github.com",
127 | }
128 |
129 | ctx := context.Background()
130 |
131 | for _, domain := range testDomains {
132 | t.Run(domain, func(t *testing.T) {
133 | result, err := resolver.Resolve(ctx, domain, dns.TypeNS)
134 | if err != nil {
135 | t.Fatalf("Failed to resolve %s NS: %v", domain, err)
136 | }
137 |
138 | if len(result.Answer) == 0 {
139 | t.Fatalf("No NS records found for %s", domain)
140 | }
141 |
142 | var nsRecords []string
143 | for _, rr := range result.Answer {
144 | if ns, ok := rr.(*dns.NS); ok {
145 | nsRecords = append(nsRecords, ns.Ns)
146 | }
147 | }
148 |
149 | if len(nsRecords) == 0 {
150 | t.Fatalf("No NS records in answer section for %s", domain)
151 | }
152 |
153 | systemNS, err := net.LookupNS(domain)
154 | if err != nil {
155 | t.Fatalf("System NS lookup failed for %s: %v", domain, err)
156 | }
157 |
158 | var systemNSNames []string
159 | for _, ns := range systemNS {
160 | systemNSNames = append(systemNSNames, ns.Host)
161 | }
162 |
163 | if !compareStringSets(nsRecords, systemNSNames) {
164 | t.Logf("Resolver NS: %v", nsRecords)
165 | t.Logf("System NS: %v", systemNSNames)
166 | t.Logf("Note: NS sets differ - this may be due to different DNS servers or timing")
167 | }
168 | })
169 | }
170 | }
171 |
172 | func TestResolverCNAME(t *testing.T) {
173 | resolver := New()
174 | testDomains := []string{
175 | "www.github.com",
176 | }
177 |
178 | ctx := context.Background()
179 |
180 | for _, domain := range testDomains {
181 | t.Run(domain, func(t *testing.T) {
182 | result, err := resolver.Resolve(ctx, domain, dns.TypeCNAME)
183 | if err != nil {
184 | t.Fatalf("Failed to resolve %s CNAME: %v", domain, err)
185 | }
186 |
187 | var cnameTarget string
188 | for _, rr := range result.Answer {
189 | if cname, ok := rr.(*dns.CNAME); ok {
190 | cnameTarget = cname.Target
191 | break
192 | }
193 | }
194 |
195 | systemCNAME, err := net.LookupCNAME(domain)
196 | if err != nil {
197 | if len(result.Answer) == 0 {
198 | t.Skipf("No CNAME record for %s (expected)", domain)
199 | return
200 | }
201 | t.Fatalf("System CNAME lookup failed for %s: %v", domain, err)
202 | }
203 |
204 | if cnameTarget != "" && systemCNAME != "" {
205 | if cnameTarget != systemCNAME {
206 | t.Logf("Resolver CNAME: %s", cnameTarget)
207 | t.Logf("System CNAME: %s", systemCNAME)
208 | t.Logf("Note: CNAME targets differ - this may be due to different DNS servers or timing")
209 | }
210 | }
211 | })
212 | }
213 | }
214 |
215 | func TestResolverNXDOMAIN(t *testing.T) {
216 | resolver := New()
217 | nonexistentDomain := "this-does-not-exist-12345.com"
218 |
219 | ctx := context.Background()
220 |
221 | result, err := resolver.Resolve(ctx, nonexistentDomain, dns.TypeA)
222 |
223 | if err != nil {
224 | t.Fatalf("Unexpected error for NXDOMAIN: %v", err)
225 | }
226 |
227 | if result.Rcode != dns.RcodeNameError {
228 | t.Fatalf("Expected NXDOMAIN (RcodeNameError), got %d", result.Rcode)
229 | }
230 | }
231 |
232 | func TestRootServerResolution(t *testing.T) {
233 | t.Logf("Testing TestRootServerResolution")
234 |
235 | rootServers := getRootServers(context.Background())
236 | if len(rootServers) == 0 {
237 | t.Fatal("No root servers resolved")
238 | }
239 |
240 | t.Logf("Resolved %d root servers", len(rootServers))
241 | for i, server := range rootServers {
242 | if i < 5 {
243 | t.Logf("Root server %d: %s", i+1, server)
244 | }
245 | }
246 | }
247 |
248 | func compareIPSets(a, b []net.IP) bool {
249 | if len(a) != len(b) {
250 | return false
251 | }
252 |
253 | aStr := make([]string, len(a))
254 | bStr := make([]string, len(b))
255 |
256 | for i, ip := range a {
257 | aStr[i] = ip.String()
258 | }
259 | for i, ip := range b {
260 | bStr[i] = ip.String()
261 | }
262 |
263 | sort.Strings(aStr)
264 | sort.Strings(bStr)
265 |
266 | for i := range aStr {
267 | if aStr[i] != bStr[i] {
268 | return false
269 | }
270 | }
271 |
272 | return true
273 | }
274 |
275 | func compareStringSets(a, b []string) bool {
276 | if len(a) != len(b) {
277 | return false
278 | }
279 |
280 | aCopy := make([]string, len(a))
281 | bCopy := make([]string, len(b))
282 | copy(aCopy, a)
283 | copy(bCopy, b)
284 |
285 | sort.Strings(aCopy)
286 | sort.Strings(bCopy)
287 |
288 | for i := range aCopy {
289 | if aCopy[i] != bCopy[i] {
290 | return false
291 | }
292 | }
293 |
294 | return true
295 | }
296 |
297 | func TestResolverResolveAll(t *testing.T) {
298 | resolver := New()
299 | testDomains := []string{
300 | "google.com",
301 | "github.com",
302 | }
303 |
304 | ctx := context.Background()
305 |
306 | for _, domain := range testDomains {
307 | t.Run(domain, func(t *testing.T) {
308 | resultAll, err := resolver.ResolveAll(ctx, domain, dns.TypeA)
309 | if err != nil {
310 | t.Fatalf("Failed to resolve %s with ResolveAll: %v", domain, err)
311 | }
312 |
313 | resultNormal, err := resolver.Resolve(ctx, domain, dns.TypeA)
314 | if err != nil {
315 | t.Fatalf("Failed to resolve %s with Resolve: %v", domain, err)
316 | }
317 |
318 | if len(resultAll.Answer) == 0 {
319 | t.Fatalf("No A records found for %s with ResolveAll", domain)
320 | }
321 |
322 | if len(resultNormal.Answer) == 0 {
323 | t.Fatalf("No A records found for %s with Resolve", domain)
324 | }
325 |
326 | var allIPs []net.IP
327 | for _, rr := range resultAll.Answer {
328 | if a, ok := rr.(*dns.A); ok {
329 | allIPs = append(allIPs, a.A)
330 | }
331 | }
332 |
333 | var normalIPs []net.IP
334 | for _, rr := range resultNormal.Answer {
335 | if a, ok := rr.(*dns.A); ok {
336 | normalIPs = append(normalIPs, a.A)
337 | }
338 | }
339 |
340 | if len(allIPs) < len(normalIPs) {
341 | t.Fatalf("ResolveAll returned fewer IPs (%d) than Resolve (%d) for %s",
342 | len(allIPs), len(normalIPs), domain)
343 | }
344 |
345 | t.Logf("ResolveAll found %d A records for %s", len(allIPs), domain)
346 | t.Logf("Resolve found %d A records for %s", len(normalIPs), domain)
347 | })
348 | }
349 | }
350 |
351 | func TestResolverLookupIP(t *testing.T) {
352 | resolver := New()
353 | testDomains := []string{
354 | "google.com",
355 | "github.com",
356 | "cloudflare.com",
357 | }
358 |
359 | ctx := context.Background()
360 |
361 | for _, domain := range testDomains {
362 | t.Run(domain, func(t *testing.T) {
363 | resolverIPs, err := resolver.LookupIP(ctx, domain)
364 | if err != nil {
365 | t.Fatalf("Failed to lookup IP for %s: %v", domain, err)
366 | }
367 |
368 | if len(resolverIPs) == 0 {
369 | t.Fatalf("No IP addresses found for %s", domain)
370 | }
371 |
372 | systemIPs, err := net.LookupIP(domain)
373 | if err != nil {
374 | t.Fatalf("System lookup failed for %s: %v", domain, err)
375 | }
376 |
377 | if len(systemIPs) == 0 {
378 | t.Fatalf("No IP addresses from system resolver for %s", domain)
379 | }
380 |
381 | var resolverIPv4, resolverIPv6 []net.IP
382 | for _, ip := range resolverIPs {
383 | if ip.To4() != nil {
384 | resolverIPv4 = append(resolverIPv4, ip)
385 | } else if ip.To16() != nil {
386 | resolverIPv6 = append(resolverIPv6, ip)
387 | }
388 | }
389 |
390 | var systemIPv4, systemIPv6 []net.IP
391 | for _, ip := range systemIPs {
392 | if ip.To4() != nil {
393 | systemIPv4 = append(systemIPv4, ip)
394 | } else if ip.To16() != nil {
395 | systemIPv6 = append(systemIPv6, ip)
396 | }
397 | }
398 |
399 | t.Logf("Resolver found %d IPv4 and %d IPv6 addresses for %s",
400 | len(resolverIPv4), len(resolverIPv6), domain)
401 | t.Logf("System found %d IPv4 and %d IPv6 addresses for %s",
402 | len(systemIPv4), len(systemIPv6), domain)
403 |
404 | if len(resolverIPv4) == 0 && len(systemIPv4) > 0 {
405 | t.Errorf("Resolver found no IPv4 addresses but system found %d for %s",
406 | len(systemIPv4), domain)
407 | }
408 | })
409 | }
410 | }
411 |
412 | func TestResolverLookupIPAll(t *testing.T) {
413 | resolver := New()
414 | testDomains := []string{
415 | "google.com",
416 | "github.com",
417 | "cloudflare.com",
418 | }
419 | ctx := context.Background()
420 |
421 | for _, domain := range testDomains {
422 | t.Run(domain, func(t *testing.T) {
423 | allIPs, err := resolver.LookupIPAll(ctx, domain)
424 | if err != nil {
425 | t.Fatalf("Failed to lookup IP with LookupIPAll for %s: %v", domain, err)
426 | }
427 |
428 | normalIPs, err := resolver.LookupIP(ctx, domain)
429 | if err != nil {
430 | t.Fatalf("Failed to lookup IP with LookupIP for %s: %v", domain, err)
431 | }
432 |
433 | if len(allIPs) == 0 {
434 | t.Fatalf("No IP addresses found with LookupIPAll for %s", domain)
435 | }
436 |
437 | if len(normalIPs) == 0 {
438 | t.Fatalf("No IP addresses found with LookupIP for %s", domain)
439 | }
440 |
441 | var allIPv4, allIPv6 []net.IP
442 | for _, ip := range allIPs {
443 | if ip.To4() != nil {
444 | allIPv4 = append(allIPv4, ip)
445 | } else if ip.To16() != nil {
446 | allIPv6 = append(allIPv6, ip)
447 | }
448 | }
449 |
450 | var normalIPv4, normalIPv6 []net.IP
451 | for _, ip := range normalIPs {
452 | if ip.To4() != nil {
453 | normalIPv4 = append(normalIPv4, ip)
454 | } else if ip.To16() != nil {
455 | normalIPv6 = append(normalIPv6, ip)
456 | }
457 | }
458 |
459 | if len(allIPv4) < len(normalIPv4) {
460 | t.Fatalf("LookupIPAll returned fewer IPv4 addresses (%d) than LookupIP (%d) for %s",
461 | len(allIPv4), len(normalIPv4), domain)
462 | }
463 |
464 | if len(allIPv6) < len(normalIPv6) {
465 | t.Fatalf("LookupIPAll returned fewer IPv6 addresses (%d) than LookupIP (%d) for %s",
466 | len(allIPv6), len(normalIPv6), domain)
467 | }
468 |
469 | t.Logf("LookupIPAll found %d IPv4 and %d IPv6 addresses for %s",
470 | len(allIPv4), len(allIPv6), domain)
471 | t.Logf("LookupIP found %d IPv4 and %d IPv6 addresses for %s",
472 | len(normalIPv4), len(normalIPv6), domain)
473 | })
474 | }
475 | }
476 |
--------------------------------------------------------------------------------
/resolver/resolver.go:
--------------------------------------------------------------------------------
1 | // Package resolver provides a recursive DNS resolver that handles missing glue records
2 | // and implements caching for improved performance.
3 | package resolver
4 |
5 | import (
6 | "context"
7 | "fmt"
8 | "net"
9 | "strconv"
10 | "strings"
11 | "sync"
12 | "time"
13 |
14 | "github.com/miekg/dns"
15 | )
16 |
17 | const (
18 | maxRecursionDepth = 30
19 | defaultQueryTimeout = 5 * time.Second
20 | maxFailures = 5 // Circuit breaker threshold
21 | circuitBreakerTTL = 60 * time.Second // How long to avoid failed nameservers
22 | )
23 |
24 | // RootServerNames contains the hostnames of the DNS root servers.
25 | // These are the authoritative nameservers for the root zone of the DNS hierarchy.
26 | var RootServerNames = []string{
27 | "a.root-servers.net",
28 | "b.root-servers.net",
29 | "c.root-servers.net",
30 | "d.root-servers.net",
31 | "e.root-servers.net",
32 | "f.root-servers.net",
33 | "g.root-servers.net",
34 | "h.root-servers.net",
35 | "i.root-servers.net",
36 | "j.root-servers.net",
37 | "k.root-servers.net",
38 | "l.root-servers.net",
39 | "m.root-servers.net",
40 | }
41 |
42 | var (
43 | rootServers []string
44 | rootServersOnce sync.Once
45 | )
46 |
47 | // Resolver implements a recursive DNS resolver with caching and missing glue record handling.
48 | // It follows the DNS resolution process by starting from root servers and following
49 | // referrals until it reaches an authoritative answer.
50 | type Resolver struct {
51 | client dns.Client
52 | cache *dnsCache
53 | rttStats map[string]*rttStats // RTT statistics per nameserver
54 | rttMutex sync.RWMutex // Protects rttStats map
55 | }
56 |
57 | type rttStats struct {
58 | avgRTT time.Duration
59 | samples int
60 | lastSeen time.Time
61 | failures int
62 | lastFailed time.Time // When the last failure occurred
63 | mu sync.Mutex
64 | }
65 |
66 | // Result represents the outcome of a DNS query operation.
67 | // It contains the response sections and metadata from the DNS resolution process.
68 | type Result struct {
69 | Answer []dns.RR // Resource records that directly answer the query
70 | Authority []dns.RR // Authority section containing NS records for delegation
71 | Additional []dns.RR // Additional section containing glue records
72 | Rcode int // DNS response code (e.g., NOERROR, NXDOMAIN)
73 | Authoritative bool // Whether the response came from an authoritative server
74 | }
75 |
76 | // New creates a new DNS resolver with default cache size.
77 | // The resolver is configured with appropriate timeouts and will handle
78 | // missing glue records automatically.
79 | func New() *Resolver {
80 | return NewWithCacheSize(defaultCacheSize, defaultQueryTimeout)
81 | }
82 |
83 | // NewWithTimeout creates a new DNS resolver with the specified timeout.
84 | // The timeout parameter determines how long to wait for DNS responses.
85 | func NewWithTimeout(timeout time.Duration) *Resolver {
86 | return NewWithCacheSize(defaultCacheSize, timeout)
87 | }
88 |
89 | // NewWithCacheSize creates a new DNS resolver with the specified cache size.
90 | // The cacheSize parameter determines how many DNS responses can be cached
91 | // using an LRU eviction policy.
92 | func NewWithCacheSize(cacheSize int, timeout time.Duration) *Resolver {
93 | return &Resolver{
94 | client: dns.Client{
95 | Timeout: timeout,
96 | Dialer: &net.Dialer{
97 | Timeout: timeout,
98 | },
99 | },
100 | cache: newDNSCache(cacheSize),
101 | rttStats: make(map[string]*rttStats),
102 | }
103 | }
104 |
105 | // getRootServers returns the cached list of root server IP addresses.
106 | // It uses sync.Once to ensure root servers are resolved only once per program execution.
107 | func getRootServers(ctx context.Context) []string {
108 | rootServersOnce.Do(func() {
109 | rootServers = resolveRootServers(ctx)
110 | })
111 | return rootServers
112 | }
113 |
114 | // resolveRootServers resolves all root server hostnames to IP addresses in parallel.
115 | // It looks up both IPv4 and IPv6 addresses for each root server and returns
116 | // them as "ip:port" strings ready for DNS queries.
117 | func resolveRootServers(ctx context.Context) []string {
118 | var servers []string
119 | var mu sync.Mutex
120 | var wg sync.WaitGroup
121 |
122 | // Create a context with timeout for root server resolution
123 | resolveCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
124 | defer cancel()
125 |
126 | // Resolve all root servers in parallel
127 | for _, name := range RootServerNames {
128 | wg.Add(1)
129 | go func(hostname string) {
130 | defer wg.Done()
131 |
132 | netResolver := &net.Resolver{}
133 | ips, err := netResolver.LookupIPAddr(resolveCtx, hostname)
134 | if err != nil {
135 | return
136 | }
137 |
138 | mu.Lock()
139 | for _, ip := range ips {
140 | servers = append(servers, net.JoinHostPort(ip.IP.String(), "53"))
141 | }
142 | mu.Unlock()
143 | }(name)
144 | }
145 | wg.Wait()
146 |
147 | return servers
148 | }
149 |
150 | // Resolve performs a recursive DNS lookup for the given domain and query type.
151 | // It starts from the root servers and follows the DNS delegation chain until
152 | // it finds an authoritative answer. Results are cached based on their TTL values.
153 | //
154 | // The domain parameter should be a valid domain name (will be converted to FQDN).
155 | // The qtype parameter specifies the DNS record type (e.g., dns.TypeA, dns.TypeAAAA).
156 | //
157 | // Returns a Result containing the DNS response sections and metadata, or an error
158 | // if the resolution fails.
159 | func (r *Resolver) Resolve(ctx context.Context, domain string, qtype uint16) (*Result, error) {
160 | domain = dns.Fqdn(domain)
161 |
162 | cacheKey := r.makeCacheKey(domain, qtype)
163 | if cached, found := r.cache.get(cacheKey); found {
164 | return cached, nil
165 | }
166 |
167 | result, err := r.resolveRecursive(ctx, domain, qtype, getRootServers(ctx), 0)
168 | if err != nil {
169 | return nil, err
170 | }
171 |
172 | if result != nil {
173 | ttl := r.calculateTTL(result)
174 | if ttl > 0 {
175 | switch result.Rcode {
176 | case dns.RcodeSuccess:
177 | r.cache.put(cacheKey, result, ttl)
178 | case dns.RcodeNameError:
179 | // Cache NXDOMAIN responses with shorter TTL
180 | negativeTTL := ttl
181 | if negativeTTL > 5*time.Minute {
182 | negativeTTL = 5 * time.Minute
183 | }
184 | r.cache.putNegative(cacheKey, result, negativeTTL)
185 | }
186 | }
187 | }
188 |
189 | return result, nil
190 | }
191 |
192 | // ResolveAll performs a recursive DNS lookup for the given domain and query type,
193 | // querying ALL authoritative nameservers and returning the union of all answers.
194 | // Unlike Resolve which returns after the first successful response, ResolveAll
195 | // queries every authoritative nameserver at each level and merges all results.
196 | //
197 | // The domain parameter should be a valid domain name (will be converted to FQDN).
198 | // The qtype parameter specifies the DNS record type (e.g., dns.TypeA, dns.TypeAAAA).
199 | //
200 | // Returns a Result containing the merged DNS response sections from all nameservers,
201 | // or an error if the resolution fails.
202 | func (r *Resolver) ResolveAll(ctx context.Context, domain string, qtype uint16) (*Result, error) {
203 | domain = dns.Fqdn(domain)
204 |
205 | cacheKey := r.makeCacheKey(domain+"_ALL", qtype)
206 | if cached, found := r.cache.get(cacheKey); found {
207 | return cached, nil
208 | }
209 |
210 | result, err := r.resolveRecursiveAll(ctx, domain, qtype, getRootServers(ctx), 0)
211 | if err != nil {
212 | return nil, err
213 | }
214 |
215 | if result != nil {
216 | ttl := r.calculateTTL(result)
217 | if ttl > 0 {
218 | switch result.Rcode {
219 | case dns.RcodeSuccess:
220 | r.cache.put(cacheKey, result, ttl)
221 | case dns.RcodeNameError:
222 | // Cache NXDOMAIN responses with shorter TTL
223 | negativeTTL := ttl
224 | if negativeTTL > 5*time.Minute {
225 | negativeTTL = 5 * time.Minute
226 | }
227 | r.cache.putNegative(cacheKey, result, negativeTTL)
228 | }
229 | }
230 | }
231 |
232 | return result, nil
233 | }
234 |
235 | // LookupIP looks up host using the resolver and returns a slice of that host's IP addresses.
236 | // It works like net.LookupIP but uses the recursive resolver instead of the system resolver.
237 | // The function queries both A and AAAA records and returns all found IP addresses.
238 | func (r *Resolver) LookupIP(ctx context.Context, host string) ([]net.IP, error) {
239 | var ips []net.IP
240 |
241 | // Query A records (IPv4)
242 | resultA, err := r.Resolve(ctx, host, dns.TypeA)
243 | if err == nil && resultA.Rcode == dns.RcodeSuccess {
244 | for _, rr := range resultA.Answer {
245 | if a, ok := rr.(*dns.A); ok {
246 | ips = append(ips, a.A)
247 | }
248 | }
249 | }
250 |
251 | // Query AAAA records (IPv6)
252 | resultAAAA, err := r.Resolve(ctx, host, dns.TypeAAAA)
253 | if err == nil && resultAAAA.Rcode == dns.RcodeSuccess {
254 | for _, rr := range resultAAAA.Answer {
255 | if aaaa, ok := rr.(*dns.AAAA); ok {
256 | ips = append(ips, aaaa.AAAA)
257 | }
258 | }
259 | }
260 |
261 | if len(ips) == 0 {
262 | return nil, fmt.Errorf("no IP addresses found for %s", host)
263 | }
264 |
265 | return ips, nil
266 | }
267 |
268 | // LookupIPAll looks up host using the resolver and returns a slice of that host's IP addresses
269 | // from ALL authoritative nameservers. It works like LookupIP but uses ResolveAll instead of Resolve,
270 | // ensuring that IP addresses from all nameservers are collected and returned.
271 | // The function queries both A and AAAA records in parallel and returns all found IP addresses.
272 | func (r *Resolver) LookupIPAll(ctx context.Context, host string) ([]net.IP, error) {
273 | // Query A and AAAA records in parallel
274 | type resolveResult struct {
275 | result *Result
276 | err error
277 | }
278 |
279 | aChan := make(chan resolveResult, 1)
280 | aaaaChan := make(chan resolveResult, 1)
281 |
282 | // Query A records (IPv4) from all nameservers
283 | go func() {
284 | result, err := r.ResolveAll(ctx, host, dns.TypeA)
285 | aChan <- resolveResult{result: result, err: err}
286 | }()
287 |
288 | // Query AAAA records (IPv6) from all nameservers
289 | go func() {
290 | result, err := r.ResolveAll(ctx, host, dns.TypeAAAA)
291 | aaaaChan <- resolveResult{result: result, err: err}
292 | }()
293 |
294 | var ips []net.IP
295 |
296 | // Collect A and AAAA record results with context cancellation support
297 | for i := 0; i < 2; i++ {
298 | select {
299 | case aResult := <-aChan:
300 | if aResult.err == nil && aResult.result.Rcode == dns.RcodeSuccess {
301 | for _, rr := range aResult.result.Answer {
302 | if a, ok := rr.(*dns.A); ok {
303 | ips = append(ips, a.A)
304 | }
305 | }
306 | }
307 | case aaaaResult := <-aaaaChan:
308 | if aaaaResult.err == nil && aaaaResult.result.Rcode == dns.RcodeSuccess {
309 | for _, rr := range aaaaResult.result.Answer {
310 | if aaaa, ok := rr.(*dns.AAAA); ok {
311 | ips = append(ips, aaaa.AAAA)
312 | }
313 | }
314 | }
315 | case <-ctx.Done():
316 | return nil, ctx.Err()
317 | }
318 | }
319 |
320 | if len(ips) == 0 {
321 | return nil, fmt.Errorf("no IP addresses found for %s", host)
322 | }
323 |
324 | return ips, nil
325 | }
326 |
327 | func (r *Resolver) makeCacheKey(domain string, qtype uint16) string {
328 | return domain + ":" + strconv.FormatUint(uint64(qtype), 10)
329 | }
330 |
331 | func (r *Resolver) updateRTT(nameserver string, rtt time.Duration, success bool) {
332 | r.rttMutex.Lock()
333 | stats, exists := r.rttStats[nameserver]
334 | if !exists {
335 | stats = &rttStats{}
336 | r.rttStats[nameserver] = stats
337 | }
338 | r.rttMutex.Unlock()
339 |
340 | stats.mu.Lock()
341 | defer stats.mu.Unlock()
342 |
343 | if success {
344 | stats.lastSeen = time.Now()
345 | stats.failures = 0
346 |
347 | if stats.samples == 0 {
348 | stats.avgRTT = rtt
349 | stats.samples = 1
350 | } else {
351 | // Exponential weighted moving average with alpha = 0.125
352 | stats.avgRTT = stats.avgRTT*7/8 + rtt/8
353 | stats.samples++
354 | }
355 | } else {
356 | stats.failures++
357 | stats.lastFailed = time.Now()
358 | }
359 | }
360 |
361 | func (r *Resolver) sortNameserversByRTT(nameservers []string) []string {
362 | if len(nameservers) <= 1 {
363 | return nameservers
364 | }
365 |
366 | type nsWithRTT struct {
367 | ns string
368 | rtt time.Duration
369 | failures int
370 | hasStat bool
371 | circuitOpen bool
372 | }
373 |
374 | var nsStats []nsWithRTT
375 | now := time.Now()
376 | r.rttMutex.RLock()
377 | for _, ns := range nameservers {
378 | stat := nsWithRTT{ns: ns}
379 | if stats, exists := r.rttStats[ns]; exists {
380 | stats.mu.Lock()
381 | stat.rtt = stats.avgRTT
382 | stat.failures = stats.failures
383 | stat.hasStat = true
384 |
385 | // Circuit breaker logic: avoid nameservers that have failed too many times recently
386 | if stats.failures >= maxFailures &&
387 | now.Sub(stats.lastFailed) < circuitBreakerTTL {
388 | stat.circuitOpen = true
389 | }
390 | stats.mu.Unlock()
391 | }
392 | nsStats = append(nsStats, stat)
393 | }
394 | r.rttMutex.RUnlock()
395 |
396 | // Sort by: circuit breaker status, then failures, then RTT, then stats availability
397 | for i := 0; i < len(nsStats)-1; i++ {
398 | for j := i + 1; j < len(nsStats); j++ {
399 | // Always prefer nameservers with open circuits last
400 | if nsStats[i].circuitOpen && !nsStats[j].circuitOpen {
401 | nsStats[i], nsStats[j] = nsStats[j], nsStats[i]
402 | continue
403 | }
404 | if !nsStats[i].circuitOpen && nsStats[j].circuitOpen {
405 | continue
406 | }
407 |
408 | // Prefer nameservers with fewer failures
409 | if nsStats[i].failures > nsStats[j].failures {
410 | nsStats[i], nsStats[j] = nsStats[j], nsStats[i]
411 | continue
412 | }
413 | if nsStats[i].failures < nsStats[j].failures {
414 | continue
415 | }
416 |
417 | // If same failure count, prefer ones with stats
418 | if !nsStats[i].hasStat && nsStats[j].hasStat {
419 | nsStats[i], nsStats[j] = nsStats[j], nsStats[i]
420 | continue
421 | }
422 | if nsStats[i].hasStat && !nsStats[j].hasStat {
423 | continue
424 | }
425 |
426 | // If both have stats, prefer lower RTT
427 | if nsStats[i].hasStat && nsStats[j].hasStat && nsStats[i].rtt > nsStats[j].rtt {
428 | nsStats[i], nsStats[j] = nsStats[j], nsStats[i]
429 | }
430 | }
431 | }
432 |
433 | result := make([]string, len(nsStats))
434 | for i, stat := range nsStats {
435 | result[i] = stat.ns
436 | }
437 | return result
438 | }
439 |
440 | func (r *Resolver) calculateTTL(result *Result) time.Duration {
441 | if result == nil {
442 | return 0
443 | }
444 |
445 | minTTL := uint32(3600)
446 |
447 | for _, rr := range result.Answer {
448 | if rr.Header().Ttl < minTTL {
449 | minTTL = rr.Header().Ttl
450 | }
451 | }
452 |
453 | for _, rr := range result.Authority {
454 | if rr.Header().Ttl < minTTL {
455 | minTTL = rr.Header().Ttl
456 | }
457 | // For NXDOMAIN, use SOA record's minimum TTL if available
458 | if result.Rcode == dns.RcodeNameError {
459 | if soa, ok := rr.(*dns.SOA); ok {
460 | if soa.Minttl < minTTL {
461 | minTTL = soa.Minttl
462 | }
463 | }
464 | }
465 | }
466 |
467 | if minTTL == 3600 && len(result.Answer) == 0 && len(result.Authority) == 0 {
468 | return 5 * time.Minute
469 | }
470 |
471 | if minTTL < 60 {
472 | minTTL = 60
473 | }
474 |
475 | return time.Duration(minTTL) * time.Second
476 | }
477 |
478 | func (r *Resolver) resolveRecursive(ctx context.Context, domain string, qtype uint16, nameservers []string, depth int) (*Result, error) {
479 | if depth > maxRecursionDepth {
480 | return nil, fmt.Errorf("maximum recursion depth exceeded")
481 | }
482 |
483 | if len(nameservers) == 0 {
484 | return nil, fmt.Errorf("no nameservers available")
485 | }
486 |
487 | // Sort nameservers by RTT for better performance
488 | sortedNS := r.sortNameserversByRTT(nameservers)
489 |
490 | for _, ns := range sortedNS {
491 | select {
492 | case <-ctx.Done():
493 | return nil, ctx.Err()
494 | default:
495 | }
496 |
497 | result, err := r.queryNameserver(ctx, ns, domain, qtype)
498 | if err != nil {
499 | continue
500 | }
501 |
502 | if result.Rcode != dns.RcodeSuccess {
503 | if result.Rcode == dns.RcodeNameError {
504 | return result, nil
505 | }
506 | continue
507 | }
508 |
509 | if len(result.Answer) > 0 {
510 | result.Answer = r.followCNAME(ctx, result.Answer, qtype, depth)
511 | return result, nil
512 | }
513 |
514 | if len(result.Authority) > 0 {
515 | nsRecords := r.extractNSRecords(result.Authority)
516 | if len(nsRecords) == 0 {
517 | continue
518 | }
519 |
520 | nextNS := r.resolveNameservers(ctx, nsRecords, result.Additional)
521 | if len(nextNS) == 0 {
522 | continue
523 | }
524 |
525 | return r.resolveRecursive(ctx, domain, qtype, nextNS, depth+1)
526 | }
527 | }
528 |
529 | return nil, fmt.Errorf("no answer found for %s", domain)
530 | }
531 |
532 | func (r *Resolver) queryNameserver(ctx context.Context, nameserver, domain string, qtype uint16) (*Result, error) {
533 | if !strings.Contains(nameserver, ":") {
534 | nameserver = nameserver + ":53"
535 | }
536 |
537 | m := new(dns.Msg)
538 | m.SetQuestion(domain, qtype)
539 | m.RecursionDesired = false
540 |
541 | start := time.Now()
542 | resp, _, err := r.client.ExchangeContext(ctx, m, nameserver)
543 | rtt := time.Since(start)
544 |
545 | if err != nil {
546 | r.updateRTT(nameserver, 0, false)
547 | return nil, err
548 | }
549 |
550 | r.updateRTT(nameserver, rtt, true)
551 |
552 | return &Result{
553 | Answer: resp.Answer,
554 | Authority: resp.Ns,
555 | Additional: resp.Extra,
556 | Rcode: resp.Rcode,
557 | Authoritative: resp.Authoritative,
558 | }, nil
559 | }
560 |
561 | func (r *Resolver) followCNAME(ctx context.Context, answers []dns.RR, originalType uint16, depth int) []dns.RR {
562 | result := make([]dns.RR, 0, len(answers))
563 |
564 | for _, rr := range answers {
565 | select {
566 | case <-ctx.Done():
567 | return result // Return what we have so far
568 | default:
569 | }
570 |
571 | result = append(result, rr)
572 |
573 | if cname, ok := rr.(*dns.CNAME); ok && originalType != dns.TypeCNAME {
574 | cnameResult, err := r.resolveRecursive(ctx, cname.Target, originalType, getRootServers(ctx), depth+1)
575 | if err == nil && len(cnameResult.Answer) > 0 {
576 | result = append(result, cnameResult.Answer...)
577 | }
578 | }
579 | }
580 |
581 | return result
582 | }
583 |
584 | func (r *Resolver) extractNSRecords(authority []dns.RR) []string {
585 | var nsRecords []string
586 | for _, rr := range authority {
587 | if ns, ok := rr.(*dns.NS); ok {
588 | nsRecords = append(nsRecords, dns.Fqdn(ns.Ns))
589 | }
590 | }
591 | return nsRecords
592 | }
593 |
594 | func (r *Resolver) resolveNameservers(ctx context.Context, nsRecords []string, additional []dns.RR) []string {
595 | var nameservers []string
596 | var mu sync.Mutex
597 |
598 | // Build map of glue records
599 | additionalMap := make(map[string][]net.IP)
600 | for _, rr := range additional {
601 | switch rec := rr.(type) {
602 | case *dns.A:
603 | additionalMap[rec.Hdr.Name] = append(additionalMap[rec.Hdr.Name], rec.A)
604 | case *dns.AAAA:
605 | additionalMap[rec.Hdr.Name] = append(additionalMap[rec.Hdr.Name], rec.AAAA)
606 | }
607 | }
608 |
609 | // Collect nameservers with glue records first
610 | var missingGlue []string
611 | for _, nsName := range nsRecords {
612 | if ips, found := additionalMap[nsName]; found {
613 | mu.Lock()
614 | for _, ip := range ips {
615 | nameservers = append(nameservers, net.JoinHostPort(ip.String(), "53"))
616 | }
617 | mu.Unlock()
618 | } else {
619 | missingGlue = append(missingGlue, nsName)
620 | }
621 | }
622 |
623 | // Resolve missing glue records in parallel
624 | if len(missingGlue) > 0 {
625 | var wg sync.WaitGroup
626 | for _, nsName := range missingGlue {
627 | wg.Add(1)
628 | go func(hostname string) {
629 | defer wg.Done()
630 | timeoutCtx, cancel := context.WithTimeout(ctx, defaultQueryTimeout)
631 | defer cancel()
632 |
633 | resolver := &net.Resolver{}
634 | ips, err := resolver.LookupIPAddr(timeoutCtx, hostname)
635 | if err == nil {
636 | mu.Lock()
637 | for _, ip := range ips {
638 | nameservers = append(nameservers, net.JoinHostPort(ip.IP.String(), "53"))
639 | }
640 | mu.Unlock()
641 | }
642 | }(nsName)
643 | }
644 | wg.Wait()
645 | }
646 |
647 | return nameservers
648 | }
649 |
650 | // mergeResults combines multiple DNS query results into a single Result.
651 | // It deduplicates resource records and selects the best Rcode and Authoritative status.
652 | // Used by ResolveAll to combine responses from multiple nameservers.
653 | func mergeResults(results []*Result) *Result {
654 | if len(results) == 0 {
655 | return nil
656 | }
657 |
658 | merged := &Result{
659 | Answer: []dns.RR{},
660 | Authority: []dns.RR{},
661 | Additional: []dns.RR{},
662 | Rcode: dns.RcodeServerFailure,
663 | Authoritative: false,
664 | }
665 |
666 | rrSeen := make(map[string]bool)
667 |
668 | for _, result := range results {
669 | if result == nil {
670 | continue
671 | }
672 |
673 | if result.Rcode == dns.RcodeSuccess {
674 | merged.Rcode = dns.RcodeSuccess
675 | } else if merged.Rcode == dns.RcodeServerFailure && result.Rcode == dns.RcodeNameError {
676 | merged.Rcode = dns.RcodeNameError
677 | }
678 |
679 | if result.Authoritative {
680 | merged.Authoritative = true
681 | }
682 |
683 | for _, rr := range result.Answer {
684 | key := rr.String()
685 | if !rrSeen[key] {
686 | rrSeen[key] = true
687 | merged.Answer = append(merged.Answer, rr)
688 | }
689 | }
690 |
691 | for _, rr := range result.Authority {
692 | key := rr.String()
693 | if !rrSeen[key] {
694 | rrSeen[key] = true
695 | merged.Authority = append(merged.Authority, rr)
696 | }
697 | }
698 |
699 | for _, rr := range result.Additional {
700 | key := rr.String()
701 | if !rrSeen[key] {
702 | rrSeen[key] = true
703 | merged.Additional = append(merged.Additional, rr)
704 | }
705 | }
706 | }
707 |
708 | return merged
709 | }
710 |
711 | // resolveRecursiveAll performs recursive resolution by querying ALL nameservers
712 | // at each level and merging their responses, unlike resolveRecursive which stops
713 | // at the first successful response.
714 | func (r *Resolver) resolveRecursiveAll(ctx context.Context, domain string, qtype uint16, nameservers []string, depth int) (*Result, error) {
715 | if depth > maxRecursionDepth {
716 | return nil, fmt.Errorf("maximum recursion depth exceeded")
717 | }
718 |
719 | if len(nameservers) == 0 {
720 | return nil, fmt.Errorf("no nameservers available")
721 | }
722 |
723 | // Query all nameservers in parallel
724 | type queryResult struct {
725 | result *Result
726 | err error
727 | }
728 |
729 | resultChan := make(chan queryResult, len(nameservers))
730 |
731 | // Start goroutines for each nameserver
732 | for _, ns := range nameservers {
733 | go func(nameserver string) {
734 | result, err := r.queryNameserver(ctx, nameserver, domain, qtype)
735 | resultChan <- queryResult{result: result, err: err}
736 | }(ns)
737 | }
738 |
739 | // Collect results from all goroutines
740 | var allResults []*Result
741 | var hasSuccessfulQuery bool
742 |
743 | for i := 0; i < len(nameservers); i++ {
744 | select {
745 | case qr := <-resultChan:
746 | if qr.err != nil {
747 | continue
748 | }
749 | hasSuccessfulQuery = true
750 | allResults = append(allResults, qr.result)
751 | case <-ctx.Done():
752 | return nil, ctx.Err()
753 | }
754 | }
755 |
756 | if !hasSuccessfulQuery {
757 | return nil, fmt.Errorf("no nameservers responded for %s", domain)
758 | }
759 |
760 | merged := mergeResults(allResults)
761 | if merged == nil {
762 | return nil, fmt.Errorf("no valid responses for %s", domain)
763 | }
764 |
765 | if merged.Rcode != dns.RcodeSuccess {
766 | return merged, nil
767 | }
768 |
769 | if len(merged.Answer) > 0 {
770 | merged.Answer = r.followCNAME(ctx, merged.Answer, qtype, depth)
771 | return merged, nil
772 | }
773 |
774 | if len(merged.Authority) > 0 {
775 | nsRecords := r.extractNSRecords(merged.Authority)
776 | if len(nsRecords) == 0 {
777 | return merged, nil
778 | }
779 |
780 | nextNS := r.resolveNameservers(ctx, nsRecords, merged.Additional)
781 | if len(nextNS) == 0 {
782 | return merged, nil
783 | }
784 |
785 | return r.resolveRecursiveAll(ctx, domain, qtype, nextNS, depth+1)
786 | }
787 |
788 | return merged, nil
789 | }
790 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------