aboutsummaryrefslogtreecommitdiff
path: root/plugin
diff options
context:
space:
mode:
authorGravatar Yong Tang <yong.tang.github@outlook.com> 2020-07-08 09:00:26 -0700
committerGravatar GitHub <noreply@github.com> 2020-07-08 09:00:26 -0700
commit614d08cba29ed4904d11008e795c081c4f392b77 (patch)
treee4601abda23ec9d18e2929433c260a37928e1344 /plugin
parent68f1dd5ddf0451cc3a1b24a72c2965b8d896ffba (diff)
downloadcoredns-614d08cba29ed4904d11008e795c081c4f392b77.tar.gz
coredns-614d08cba29ed4904d11008e795c081c4f392b77.tar.zst
coredns-614d08cba29ed4904d11008e795c081c4f392b77.zip
Revert "Implement notifies for transfer plugin (#3972)" (#3995)
This reverts commit 68f1dd5ddf0451cc3a1b24a72c2965b8d896ffba. Signed-off-by: Yong Tang <yong.tang.github@outlook.com>
Diffstat (limited to 'plugin')
-rw-r--r--plugin/auto/README.md18
-rw-r--r--plugin/auto/auto.go11
-rw-r--r--plugin/auto/setup.go20
-rw-r--r--plugin/auto/setup_test.go47
-rw-r--r--plugin/auto/walk.go5
-rw-r--r--plugin/auto/xfr.go19
-rw-r--r--plugin/auto/zone.go5
-rw-r--r--plugin/backend.go9
-rw-r--r--plugin/etcd/xfr.go12
-rw-r--r--plugin/file/README.md22
-rw-r--r--plugin/file/file.go7
-rw-r--r--plugin/file/notify.go47
-rw-r--r--plugin/file/reload.go10
-rw-r--r--plugin/file/reload_test.go3
-rw-r--r--plugin/file/secondary_test.go4
-rw-r--r--plugin/file/setup.go59
-rw-r--r--plugin/file/xfr.go121
-rw-r--r--plugin/file/zone.go25
-rw-r--r--plugin/kubernetes/README.md13
-rw-r--r--plugin/kubernetes/handler.go2
-rw-r--r--plugin/kubernetes/handler_test.go3
-rw-r--r--plugin/kubernetes/kubernetes.go7
-rw-r--r--plugin/kubernetes/setup.go10
-rw-r--r--plugin/kubernetes/setup_transfer_test.go47
-rw-r--r--plugin/kubernetes/xfr.go252
-rw-r--r--plugin/kubernetes/xfr_test.go255
-rw-r--r--plugin/pkg/parse/parse.go32
-rw-r--r--plugin/pkg/parse/parse_test.go45
-rw-r--r--plugin/secondary/README.md22
-rw-r--r--plugin/secondary/setup.go19
-rw-r--r--plugin/secondary/setup_test.go2
-rw-r--r--plugin/transfer/README.md30
-rw-r--r--plugin/transfer/notify.go58
-rw-r--r--plugin/transfer/select_test.go58
-rw-r--r--plugin/transfer/setup.go11
-rw-r--r--plugin/transfer/setup_test.go12
-rw-r--r--plugin/transfer/transfer.go149
-rw-r--r--plugin/transfer/transfer_test.go141
38 files changed, 947 insertions, 665 deletions
diff --git a/plugin/auto/README.md b/plugin/auto/README.md
index 43c17cfa7..26c232c4d 100644
--- a/plugin/auto/README.md
+++ b/plugin/auto/README.md
@@ -16,6 +16,7 @@ zonefile. New or changed zones are automatically picked up from disk.
~~~
auto [ZONES...] {
directory DIR [REGEXP ORIGIN_TEMPLATE]
+ transfer to ADDRESS...
reload DURATION
}
~~~
@@ -28,12 +29,14 @@ are used.
like `{<number>}` are replaced with the respective matches in the file name, e.g. `{1}` is the
first match, `{2}` is the second. The default is: `db\.(.*) {1}` i.e. from a file with the
name `db.example.com`, the extracted origin will be `example.com`.
+* `transfer` enables zone transfers. It may be specified multiples times. `To` or `from` signals
+ the direction. **ADDRESS** must be denoted in CIDR notation (e.g., 127.0.0.1/32) or just as plain
+ addresses. The special wildcard `*` means: the entire internet (only valid for 'transfer to').
+ When an address is specified a notify message will be send whenever the zone is reloaded.
* `reload` interval to perform reloads of zones if SOA version changes and zonefiles. It specifies how often CoreDNS should scan the directory to watch for file removal and addition. Default is one minute.
Value of `0` means to not scan for changes and reload. eg. `30s` checks zonefile every 30 seconds
and reloads zone when serial changes.
-For enabling zone transfers look at the *transfer* plugin.
-
All directives from the *file* plugin are supported. Note that *auto* will load all zones found,
even though the directive might only receive queries for a specific zone. I.e:
@@ -56,10 +59,8 @@ notifies to 10.240.1.1
org {
auto {
directory /etc/coredns/zones/org
- }
- transfer {
- to *
- to 10.240.1.1
+ transfer to *
+ transfer to 10.240.1.1
}
}
~~~
@@ -75,8 +76,3 @@ org {
}
}
~~~
-
-## Also
-
-Use the *root* plugin to help you specify the location of the zone files. See the *transfer* plugin
-to enable outgoing zone transfers.
diff --git a/plugin/auto/auto.go b/plugin/auto/auto.go
index 4316d8d2f..74a48a205 100644
--- a/plugin/auto/auto.go
+++ b/plugin/auto/auto.go
@@ -10,7 +10,6 @@ import (
"github.com/coredns/coredns/plugin/file"
"github.com/coredns/coredns/plugin/metrics"
"github.com/coredns/coredns/plugin/pkg/upstream"
- "github.com/coredns/coredns/plugin/transfer"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
@@ -22,8 +21,7 @@ type (
Next plugin.Handler
*Zones
- metrics *metrics.Metrics
- transfer *transfer.Transfer
+ metrics *metrics.Metrics
loader
}
@@ -32,6 +30,8 @@ type (
template string
re *regexp.Regexp
+ // In the future this should be something like ZoneMeta that contains all this stuff.
+ transferTo []string
ReloadInterval time.Duration
upstream *upstream.Upstream // Upstream for looking up names during the resolution process.
}
@@ -59,6 +59,11 @@ func (a Auto) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (i
return dns.RcodeServerFailure, nil
}
+ if state.QType() == dns.TypeAXFR || state.QType() == dns.TypeIXFR {
+ xfr := file.Xfr{Zone: z}
+ return xfr.ServeDNS(ctx, w, r)
+ }
+
answer, ns, extra, result := z.Lookup(ctx, state, qname)
m := new(dns.Msg)
diff --git a/plugin/auto/setup.go b/plugin/auto/setup.go
index 2e4b1bf03..e6495b192 100644
--- a/plugin/auto/setup.go
+++ b/plugin/auto/setup.go
@@ -10,8 +10,8 @@ import (
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/metrics"
clog "github.com/coredns/coredns/plugin/pkg/log"
+ "github.com/coredns/coredns/plugin/pkg/parse"
"github.com/coredns/coredns/plugin/pkg/upstream"
- "github.com/coredns/coredns/plugin/transfer"
"github.com/caddyserver/caddy"
)
@@ -28,13 +28,10 @@ func setup(c *caddy.Controller) error {
c.OnStartup(func() error {
m := dnsserver.GetConfig(c).Handler("prometheus")
- if m != nil {
- (&a).metrics = m.(*metrics.Metrics)
- }
- t := dnsserver.GetConfig(c).Handler("transfer")
- if t != nil {
- (&a).transfer = t.(*transfer.Transfer)
+ if m == nil {
+ return nil
}
+ (&a).metrics = m.(*metrics.Metrics)
return nil
})
@@ -150,6 +147,15 @@ func autoParse(c *caddy.Controller) (Auto, error) {
// remove soon
c.RemainingArgs() // eat remaining args
+ case "transfer":
+ t, _, e := parse.Transfer(c, false)
+ if e != nil {
+ return a, e
+ }
+ if t != nil {
+ a.loader.transferTo = append(a.loader.transferTo, t...)
+ }
+
default:
return Auto{}, c.Errf("unknown property '%s'", c.Val())
}
diff --git a/plugin/auto/setup_test.go b/plugin/auto/setup_test.go
index ff3a7c396..528dce23b 100644
--- a/plugin/auto/setup_test.go
+++ b/plugin/auto/setup_test.go
@@ -15,38 +15,48 @@ func TestAutoParse(t *testing.T) {
expectedTempl string
expectedRe string
expectedReloadInterval time.Duration
+ expectedTo []string
}{
{
`auto example.org {
directory /tmp
+ transfer to 127.0.0.1
}`,
- false, "/tmp", "${1}", `db\.(.*)`, 60 * time.Second,
+ false, "/tmp", "${1}", `db\.(.*)`, 60 * time.Second, []string{"127.0.0.1:53"},
},
{
`auto 10.0.0.0/24 {
directory /tmp
}`,
- false, "/tmp", "${1}", `db\.(.*)`, 60 * time.Second,
+ false, "/tmp", "${1}", `db\.(.*)`, 60 * time.Second, nil,
},
{
`auto {
directory /tmp
reload 0
}`,
- false, "/tmp", "${1}", `db\.(.*)`, 0 * time.Second,
+ false, "/tmp", "${1}", `db\.(.*)`, 0 * time.Second, nil,
},
{
`auto {
directory /tmp (.*) bliep
}`,
- false, "/tmp", "bliep", `(.*)`, 60 * time.Second,
+ false, "/tmp", "bliep", `(.*)`, 60 * time.Second, nil,
},
{
`auto {
directory /tmp (.*) bliep
reload 10s
}`,
- false, "/tmp", "bliep", `(.*)`, 10 * time.Second,
+ false, "/tmp", "bliep", `(.*)`, 10 * time.Second, nil,
+ },
+ {
+ `auto {
+ directory /tmp (.*) bliep
+ transfer to 127.0.0.1
+ transfer to 127.0.0.2
+ }`,
+ false, "/tmp", "bliep", `(.*)`, 60 * time.Second, []string{"127.0.0.1:53", "127.0.0.2:53"},
},
// errors
// NO_RELOAD has been deprecated.
@@ -55,50 +65,42 @@ func TestAutoParse(t *testing.T) {
directory /tmp
no_reload
}`,
- true, "/tmp", "${1}", `db\.(.*)`, 0 * time.Second,
+ true, "/tmp", "${1}", `db\.(.*)`, 0 * time.Second, nil,
},
// TIMEOUT has been deprecated.
{
`auto {
directory /tmp (.*) bliep 10
}`,
- true, "/tmp", "bliep", `(.*)`, 10 * time.Second,
- },
- // TRANSFER has been deprecated.
- {
- `auto {
- directory /tmp (.*) bliep 10
- transfer to 127.0.0.1
- }`,
- true, "/tmp", "bliep", `(.*)`, 10 * time.Second,
+ true, "/tmp", "bliep", `(.*)`, 10 * time.Second, nil,
},
// no template specified.
{
`auto {
directory /tmp (.*)
}`,
- true, "/tmp", "", `(.*)`, 60 * time.Second,
+ true, "/tmp", "", `(.*)`, 60 * time.Second, nil,
},
// no directory specified.
{
`auto example.org {
directory
}`,
- true, "", "${1}", `db\.(.*)`, 60 * time.Second,
+ true, "", "${1}", `db\.(.*)`, 60 * time.Second, nil,
},
// illegal REGEXP.
{
`auto example.org {
directory /tmp * {1}
}`,
- true, "/tmp", "${1}", ``, 60 * time.Second,
+ true, "/tmp", "${1}", ``, 60 * time.Second, nil,
},
// unexpected argument.
{
`auto example.org {
directory /tmp (.*) {1} aa
}`,
- true, "/tmp", "${1}", ``, 60 * time.Second,
+ true, "/tmp", "${1}", ``, 60 * time.Second, nil,
},
}
@@ -123,6 +125,13 @@ func TestAutoParse(t *testing.T) {
if a.loader.ReloadInterval != test.expectedReloadInterval {
t.Fatalf("Test %d expected %v, got %v", i, test.expectedReloadInterval, a.loader.ReloadInterval)
}
+ if test.expectedTo != nil {
+ for j, got := range a.loader.transferTo {
+ if got != test.expectedTo[j] {
+ t.Fatalf("Test %d expected %v, got %v", i, test.expectedTo[j], got)
+ }
+ }
+ }
}
}
}
diff --git a/plugin/auto/walk.go b/plugin/auto/walk.go
index 9108fe941..40c62e514 100644
--- a/plugin/auto/walk.go
+++ b/plugin/auto/walk.go
@@ -53,14 +53,15 @@ func (a Auto) Walk() error {
zo.ReloadInterval = a.loader.ReloadInterval
zo.Upstream = a.loader.upstream
+ zo.TransferTo = a.loader.transferTo
- a.Zones.Add(zo, origin, a.transfer)
+ a.Zones.Add(zo, origin)
if a.metrics != nil {
a.metrics.AddZone(origin)
}
- a.transfer.Notify(origin)
+ zo.Notify()
log.Infof("Inserting zone `%s' from: %s", origin, path)
diff --git a/plugin/auto/xfr.go b/plugin/auto/xfr.go
deleted file mode 100644
index 6fef8b9e8..000000000
--- a/plugin/auto/xfr.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package auto
-
-import (
- "github.com/coredns/coredns/plugin/transfer"
-
- "github.com/miekg/dns"
-)
-
-// Transfer implements the transfer.Transfer interface.
-func (a Auto) Transfer(zone string, serial uint32) (<-chan []dns.RR, error) {
- a.Zones.RLock()
- z, ok := a.Zones.Z[zone]
- a.Zones.RUnlock()
-
- if !ok || z == nil {
- return nil, transfer.ErrNotAuthoritative
- }
- return z.Transfer(serial)
-}
diff --git a/plugin/auto/zone.go b/plugin/auto/zone.go
index dff376bf9..0a12ca39f 100644
--- a/plugin/auto/zone.go
+++ b/plugin/auto/zone.go
@@ -5,7 +5,6 @@ import (
"sync"
"github.com/coredns/coredns/plugin/file"
- "github.com/coredns/coredns/plugin/transfer"
)
// Zones maps zone names to a *Zone. This keeps track of what zones we have loaded at
@@ -43,7 +42,7 @@ func (z *Zones) Zones(name string) *file.Zone {
// Add adds a new zone into z. If zo.NoReload is false, the
// reload goroutine is started.
-func (z *Zones) Add(zo *file.Zone, name string, t *transfer.Transfer) {
+func (z *Zones) Add(zo *file.Zone, name string) {
z.Lock()
if z.Z == nil {
@@ -52,7 +51,7 @@ func (z *Zones) Add(zo *file.Zone, name string, t *transfer.Transfer) {
z.Z[name] = zo
z.names = append(z.names, name)
- zo.Reload(t)
+ zo.Reload()
z.Unlock()
}
diff --git a/plugin/backend.go b/plugin/backend.go
index 449faf37c..32443a955 100644
--- a/plugin/backend.go
+++ b/plugin/backend.go
@@ -29,11 +29,20 @@ type ServiceBackend interface {
// IsNameError return true if err indicated a record not found condition
IsNameError(err error) bool
+ Transferer
+}
+
+// Transferer defines an interface for backends that provide AXFR of all records.
+type Transferer interface {
// Serial returns a SOA serial number to construct a SOA record.
Serial(state request.Request) uint32
// MinTTL returns the minimum TTL to be used in the SOA record.
MinTTL(state request.Request) uint32
+
+ // Transfer handles a zone transfer it writes to the client just
+ // like any other handler.
+ Transfer(ctx context.Context, state request.Request) (int, error)
}
// Options are extra options that can be specified for a lookup.
diff --git a/plugin/etcd/xfr.go b/plugin/etcd/xfr.go
index 87a4d7838..358ff7a38 100644
--- a/plugin/etcd/xfr.go
+++ b/plugin/etcd/xfr.go
@@ -1,17 +1,25 @@
package etcd
import (
+ "context"
"time"
"github.com/coredns/coredns/request"
+
+ "github.com/miekg/dns"
)
-// Serial returns the serial number to use.
+// Serial implements the Transferer interface.
func (e *Etcd) Serial(state request.Request) uint32 {
return uint32(time.Now().Unix())
}
-// MinTTL returns the minimal TTL.
+// MinTTL implements the Transferer interface.
func (e *Etcd) MinTTL(state request.Request) uint32 {
return 30
}
+
+// Transfer implements the Transferer interface.
+func (e *Etcd) Transfer(ctx context.Context, state request.Request) (int, error) {
+ return dns.RcodeServerFailure, nil
+}
diff --git a/plugin/file/README.md b/plugin/file/README.md
index 3923322dd..e80b6b0dc 100644
--- a/plugin/file/README.md
+++ b/plugin/file/README.md
@@ -26,16 +26,19 @@ If you want to round-robin A and AAAA responses look at the *loadbalance* plugin
~~~
file DBFILE [ZONES... ] {
+ transfer to ADDRESS...
reload DURATION
}
~~~
+* `transfer` enables zone transfers. It may be specified multiples times. `To` or `from` signals
+ the direction. **ADDRESS** must be denoted in CIDR notation (e.g., 127.0.0.1/32) or just as plain
+ addresses. The special wildcard `*` means: the entire internet (only valid for 'transfer to').
+ When an address is specified a notify message will be sent whenever the zone is reloaded.
* `reload` interval to perform a reload of the zone if the SOA version changes. Default is one minute.
Value of `0` means to not scan for changes and reload. For example, `30s` checks the zonefile every 30 seconds
and reloads the zone when serial changes.
-If you need outgoing zone transfers, take a look at the *transfer* plugin.
-
## Examples
Load the `example.org` zone from `example.org.signed` and allow transfers to the internet, but send
@@ -43,9 +46,9 @@ notifies to 10.240.1.1
~~~ corefile
example.org {
- file example.org.signed
- transfer {
- to * 10.240.1.1
+ file example.org.signed {
+ transfer to *
+ transfer to 10.240.1.1
}
}
~~~
@@ -54,9 +57,9 @@ Or use a single zone file for multiple zones:
~~~ corefile
. {
- file example.org.signed example.org example.net
- transfer example.org example.net {
- to * 10.240.1.1
+ file example.org.signed example.org example.net {
+ transfer to *
+ transfer to 10.240.1.1
}
}
~~~
@@ -91,5 +94,4 @@ example.org {
## Also See
-See the *loadbalance* plugin if you need simple record shuffling. And the *transfer* plugin for zone
-transfers. Lastly the *root* plugin can help you specificy the location of the zone files.
+See the *loadbalance* plugin if you need simple record shuffling.
diff --git a/plugin/file/file.go b/plugin/file/file.go
index 1c586dd6d..d8de85cd3 100644
--- a/plugin/file/file.go
+++ b/plugin/file/file.go
@@ -8,7 +8,6 @@ import (
"github.com/coredns/coredns/plugin"
clog "github.com/coredns/coredns/plugin/pkg/log"
- "github.com/coredns/coredns/plugin/transfer"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
@@ -21,7 +20,6 @@ type (
File struct {
Next plugin.Handler
Zones
- transfer *transfer.Transfer
}
// Zones maps zone names to a *Zone.
@@ -79,6 +77,11 @@ func (f File) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (i
return dns.RcodeServerFailure, nil
}
+ if state.QType() == dns.TypeAXFR || state.QType() == dns.TypeIXFR {
+ xfr := Xfr{z}
+ return xfr.ServeDNS(ctx, w, r)
+ }
+
answer, ns, extra, result := z.Lookup(ctx, state, qname)
m := new(dns.Msg)
diff --git a/plugin/file/notify.go b/plugin/file/notify.go
index 7d4e35cc3..83d73ee6f 100644
--- a/plugin/file/notify.go
+++ b/plugin/file/notify.go
@@ -1,8 +1,10 @@
package file
import (
+ "fmt"
"net"
+ "github.com/coredns/coredns/plugin/pkg/rcode"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
@@ -31,3 +33,48 @@ func (z *Zone) isNotify(state request.Request) bool {
}
return false
}
+
+// Notify will send notifies to all configured TransferTo IP addresses.
+func (z *Zone) Notify() {
+ go notify(z.origin, z.TransferTo)
+}
+
+// notify sends notifies to the configured remote servers. It will try up to three times
+// before giving up on a specific remote. We will sequentially loop through "to"
+// until they all have replied (or have 3 failed attempts).
+func notify(zone string, to []string) error {
+ m := new(dns.Msg)
+ m.SetNotify(zone)
+ c := new(dns.Client)
+
+ for _, t := range to {
+ if t == "*" {
+ continue
+ }
+ if err := notifyAddr(c, m, t); err != nil {
+ log.Error(err.Error())
+ }
+ }
+ log.Infof("Sent notifies for zone %q to %v", zone, to)
+ return nil
+}
+
+func notifyAddr(c *dns.Client, m *dns.Msg, s string) error {
+ var err error
+
+ code := dns.RcodeServerFailure
+ for i := 0; i < 3; i++ {
+ ret, _, err := c.Exchange(m, s)
+ if err != nil {
+ continue
+ }
+ code = ret.Rcode
+ if code == dns.RcodeSuccess {
+ return nil
+ }
+ }
+ if err != nil {
+ return fmt.Errorf("notify for zone %q was not accepted by %q: %q", m.Question[0].Name, s, err)
+ }
+ return fmt.Errorf("notify for zone %q was not accepted by %q: rcode was %q", m.Question[0].Name, s, rcode.ToString(code))
+}
diff --git a/plugin/file/reload.go b/plugin/file/reload.go
index 426a986b0..79db040fe 100644
--- a/plugin/file/reload.go
+++ b/plugin/file/reload.go
@@ -3,12 +3,10 @@ package file
import (
"os"
"time"
-
- "github.com/coredns/coredns/plugin/transfer"
)
// Reload reloads a zone when it is changed on disk. If z.NoReload is true, no reloading will be done.
-func (z *Zone) Reload(t *transfer.Transfer) error {
+func (z *Zone) Reload() error {
if z.ReloadInterval == 0 {
return nil
}
@@ -42,11 +40,7 @@ func (z *Zone) Reload(t *transfer.Transfer) error {
z.Unlock()
log.Infof("Successfully reloaded zone %q in %q with %d SOA serial", z.origin, zFile, z.Apex.SOA.Serial)
- if t != nil {
- if err := t.Notify(z.origin); err != nil {
- log.Warningf("Failed sending notifies: %s", err)
- }
- }
+ z.Notify()
case <-z.reloadShutdown:
tick.Stop()
diff --git a/plugin/file/reload_test.go b/plugin/file/reload_test.go
index 0c644d484..f9e544372 100644
--- a/plugin/file/reload_test.go
+++ b/plugin/file/reload_test.go
@@ -9,7 +9,6 @@ import (
"time"
"github.com/coredns/coredns/plugin/test"
- "github.com/coredns/coredns/plugin/transfer"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
@@ -31,7 +30,7 @@ func TestZoneReload(t *testing.T) {
}
z.ReloadInterval = 500 * time.Millisecond
- z.Reload(&transfer.Transfer{})
+ z.Reload()
time.Sleep(time.Second)
ctx := context.TODO()
diff --git a/plugin/file/secondary_test.go b/plugin/file/secondary_test.go
index 67d151e53..820c9b9d0 100644
--- a/plugin/file/secondary_test.go
+++ b/plugin/file/secondary_test.go
@@ -11,6 +11,10 @@ import (
"github.com/miekg/dns"
)
+// TODO(miek): should test notifies as well, ie start test server (a real coredns one)...
+// setup other test server that sends notify, see if CoreDNS comes calling for a zone
+// transfer
+
func TestLess(t *testing.T) {
const (
min = 0
diff --git a/plugin/file/setup.go b/plugin/file/setup.go
index 1309dcf85..44ecf2ca1 100644
--- a/plugin/file/setup.go
+++ b/plugin/file/setup.go
@@ -7,8 +7,8 @@ import (
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
+ "github.com/coredns/coredns/plugin/pkg/parse"
"github.com/coredns/coredns/plugin/pkg/upstream"
- "github.com/coredns/coredns/plugin/transfer"
"github.com/caddyserver/caddy"
)
@@ -21,43 +21,26 @@ func setup(c *caddy.Controller) error {
return plugin.Error("file", err)
}
- f := File{Zones: zones}
- // get the transfer plugin, so we can send notifies and send notifies on startup as well.
- c.OnStartup(func() error {
- t := dnsserver.GetConfig(c).Handler("transfer")
- if t == nil {
- return nil
- }
- f.transfer = t.(*transfer.Transfer) // if found this must be OK.
- for _, n := range zones.Names {
- f.transfer.Notify(n)
- }
- return nil
- })
-
- c.OnRestartFailed(func() error {
- t := dnsserver.GetConfig(c).Handler("transfer")
- if t == nil {
- return nil
- }
- for _, n := range zones.Names {
- f.transfer.Notify(n)
- }
- return nil
- })
-
+ // Add startup functions to notify the master(s).
for _, n := range zones.Names {
z := zones.Z[n]
- c.OnShutdown(z.OnShutdown)
c.OnStartup(func() error {
- z.StartupOnce.Do(func() { z.Reload(f.transfer) })
+ z.StartupOnce.Do(func() {
+ if len(z.TransferTo) > 0 {
+ z.Notify()
+ }
+ z.Reload()
+ })
return nil
})
}
+ for _, n := range zones.Names {
+ z := zones.Z[n]
+ c.OnShutdown(z.OnShutdown)
+ }
dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
- f.Next = next
- return f
+ return File{Next: next, Zones: zones}
})
return nil
@@ -110,14 +93,24 @@ func fileParse(c *caddy.Controller) (Zones, error) {
names = append(names, origins[i])
}
+ t := []string{}
+ var e error
+
for c.NextBlock() {
switch c.Val() {
+ case "transfer":
+ t, _, e = parse.Transfer(c, false)
+ if e != nil {
+ return Zones{}, e
+ }
+
case "reload":
d, err := time.ParseDuration(c.RemainingArgs()[0])
if err != nil {
return Zones{}, plugin.Error("file", err)
}
reload = d
+
case "upstream":
// remove soon
c.RemainingArgs()
@@ -125,6 +118,12 @@ func fileParse(c *caddy.Controller) (Zones, error) {
default:
return Zones{}, c.Errf("unknown property '%s'", c.Val())
}
+
+ for _, origin := range origins {
+ if t != nil {
+ z[origin].TransferTo = append(z[origin].TransferTo, t...)
+ }
+ }
}
}
diff --git a/plugin/file/xfr.go b/plugin/file/xfr.go
index 28c3a3a9d..f7192165b 100644
--- a/plugin/file/xfr.go
+++ b/plugin/file/xfr.go
@@ -1,45 +1,118 @@
package file
import (
+ "context"
+ "fmt"
+ "sync"
+
+ "github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/file/tree"
- "github.com/coredns/coredns/plugin/transfer"
+ "github.com/coredns/coredns/request"
"github.com/miekg/dns"
)
-// Transfer implements the transfer.Transfer interface.
-func (f File) Transfer(zone string, serial uint32) (<-chan []dns.RR, error) {
- z, ok := f.Zones.Z[zone]
- if !ok || z == nil {
- return nil, transfer.ErrNotAuthoritative
- }
- return z.Transfer(serial)
+// Xfr serves up an AXFR.
+type Xfr struct {
+ *Zone
}
-// Transfer transfers a zone with serial in the returned channel and implements IXFR fallback, by just
-// sending a single SOA record.
-func (z *Zone) Transfer(serial uint32) (<-chan []dns.RR, error) {
+// ServeDNS implements the plugin.Handler interface.
+func (x Xfr) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
+ state := request.Request{W: w, Req: r}
+ if !x.TransferAllowed(state) {
+ return dns.RcodeServerFailure, nil
+ }
+ if state.QType() != dns.TypeAXFR && state.QType() != dns.TypeIXFR {
+ return 0, plugin.Error(x.Name(), fmt.Errorf("xfr called with non transfer type: %d", state.QType()))
+ }
+
+ // For IXFR we take the SOA in the IXFR message (if there), compare it what we have and then decide to do an
+ // AXFR or just reply with one SOA message back.
+ if state.QType() == dns.TypeIXFR {
+ code, _ := x.ServeIxfr(ctx, w, r)
+ if plugin.ClientWrite(code) {
+ return code, nil
+ }
+ }
+
// get soa and apex
- apex, err := z.ApexIfDefined()
+ apex, err := x.ApexIfDefined()
if err != nil {
- return nil, err
+ return dns.RcodeServerFailure, nil
}
- ch := make(chan []dns.RR)
+ ch := make(chan *dns.Envelope)
+ tr := new(dns.Transfer)
+ wg := new(sync.WaitGroup)
+ wg.Add(1)
go func() {
- if serial != 0 && apex[0].(*dns.SOA).Serial == serial { // ixfr fallback, only send SOA
- ch <- []dns.RR{apex[0]}
+ tr.Out(w, r, ch)
+ wg.Done()
+ }()
- close(ch)
- return
+ rrs := []dns.RR{}
+ l := len(apex)
+
+ ch <- &dns.Envelope{RR: apex}
+
+ x.Walk(func(e *tree.Elem, _ map[uint16][]dns.RR) error {
+ rrs = append(rrs, e.All()...)
+ if len(rrs) > 500 {
+ ch <- &dns.Envelope{RR: rrs}
+ l += len(rrs)
+ rrs = []dns.RR{}
}
+ return nil
+ })
- ch <- apex
- z.Walk(func(e *tree.Elem, _ map[uint16][]dns.RR) error { ch <- e.All(); return nil })
- ch <- []dns.RR{apex[0]}
+ if len(rrs) > 0 {
+ ch <- &dns.Envelope{RR: rrs}
+ l += len(rrs)
+ rrs = []dns.RR{}
+ }
- close(ch)
- }()
+ ch <- &dns.Envelope{RR: []dns.RR{apex[0]}} // closing SOA.
+ l++
+
+ close(ch) // Even though we close the channel here, we still have
+ wg.Wait() // to wait before we can return and close the connection.
+
+ log.Infof("Outgoing transfer of %d records of zone %s to %s done with %d SOA serial", l, x.origin, state.IP(), apex[0].(*dns.SOA).Serial)
+ return dns.RcodeSuccess, nil
+}
+
+// Name implements the plugin.Handler interface.
+func (x Xfr) Name() string { return "xfr" }
- return ch, nil
+// ServeIxfr checks if we need to serve a simpler IXFR for the incoming message.
+// See RFC 1995 Section 3: "... and the authority section containing the SOA record of client's version of the zone."
+// and Section 2, paragraph 4 where we only need to echo the SOA record back.
+// This function must be called when the qtype is IXFR. It returns a plugin.ClientWrite(code) == false, when it didn't
+// write anything and we should perform an AXFR.
+func (x Xfr) ServeIxfr(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
+ if len(r.Ns) != 1 {
+ return dns.RcodeServerFailure, nil
+ }
+ soa, ok := r.Ns[0].(*dns.SOA)
+ if !ok {
+ return dns.RcodeServerFailure, nil
+ }
+
+ x.RLock()
+ if x.Apex.SOA == nil {
+ x.RUnlock()
+ return dns.RcodeServerFailure, nil
+ }
+ serial := x.Apex.SOA.Serial
+ x.RUnlock()
+
+ if soa.Serial == serial { // Section 2, para 4; echo SOA back. We have the same zone
+ m := new(dns.Msg)
+ m.SetReply(r)
+ m.Answer = []dns.RR{soa}
+ w.WriteMsg(m)
+ return 0, nil
+ }
+ return dns.RcodeServerFailure, nil
}
diff --git a/plugin/file/zone.go b/plugin/file/zone.go
index aa5f3cac0..62720abb4 100644
--- a/plugin/file/zone.go
+++ b/plugin/file/zone.go
@@ -2,6 +2,7 @@ package file
import (
"fmt"
+ "net"
"path/filepath"
"strings"
"sync"
@@ -9,6 +10,7 @@ import (
"github.com/coredns/coredns/plugin/file/tree"
"github.com/coredns/coredns/plugin/pkg/upstream"
+ "github.com/coredns/coredns/request"
"github.com/miekg/dns"
)
@@ -24,6 +26,7 @@ type Zone struct {
sync.RWMutex
+ TransferTo []string
StartupOnce sync.Once
TransferFrom []string
@@ -55,6 +58,7 @@ func NewZone(name, file string) *Zone {
// Copy copies a zone.
func (z *Zone) Copy() *Zone {
z1 := NewZone(z.origin, z.file)
+ z1.TransferTo = z.TransferTo
z1.TransferFrom = z.TransferFrom
z1.Expired = z.Expired
@@ -65,6 +69,7 @@ func (z *Zone) Copy() *Zone {
// CopyWithoutApex copies zone z without the Apex records.
func (z *Zone) CopyWithoutApex() *Zone {
z1 := NewZone(z.origin, z.file)
+ z1.TransferTo = z.TransferTo
z1.TransferFrom = z.TransferFrom
z1.Expired = z.Expired
@@ -129,6 +134,26 @@ func (z *Zone) SetFile(path string) {
z.Unlock()
}
+// TransferAllowed checks if incoming request for transferring the zone is allowed according to the ACLs.
+func (z *Zone) TransferAllowed(state request.Request) bool {
+ for _, t := range z.TransferTo {
+ if t == "*" {
+ return true
+ }
+ // If remote IP matches we accept.
+ remote := state.IP()
+ to, _, err := net.SplitHostPort(t)
+ if err != nil {
+ continue
+ }
+ if to == remote {
+ return true
+ }
+ }
+ // TODO(miek): future matching against IP/CIDR notations
+ return false
+}
+
// ApexIfDefined returns the apex nodes from z. The SOA record is the first record, if it does not exist, an error is returned.
func (z *Zone) ApexIfDefined() ([]dns.RR, error) {
z.RLock()
diff --git a/plugin/kubernetes/README.md b/plugin/kubernetes/README.md
index 007e4bd72..654e6526f 100644
--- a/plugin/kubernetes/README.md
+++ b/plugin/kubernetes/README.md
@@ -40,6 +40,7 @@ kubernetes [ZONES...] {
endpoint_pod_names
ttl TTL
noendpoints
+ transfer to ADDRESS...
fallthrough [ZONES...]
ignore empty_service
}
@@ -89,6 +90,11 @@ kubernetes [ZONES...] {
0 seconds, and the maximum is capped at 3600 seconds. Setting TTL to 0 will prevent records from being cached.
* `noendpoints` will turn off the serving of endpoint records by disabling the watch on endpoints.
All endpoint queries and headless service queries will result in an NXDOMAIN.
+* `transfer` enables zone transfers. It may be specified multiples times. `To` signals the direction
+ (only `to` is allowed). **ADDRESS** must be denoted in CIDR notation (127.0.0.1/32 etc.) or just as
+ plain addresses. The special wildcard `*` means: the entire internet.
+ Sending DNS notifies is not supported.
+ [Deprecated](https://github.com/kubernetes/dns/blob/master/docs/specification.md#26---deprecated-records) pod records in the subdomain `pod.cluster.local` are not transferred.
* `fallthrough` **[ZONES...]** If a query for a record in the zones for which the plugin is authoritative
results in NXDOMAIN, normally that is what the response will be. However, if you specify this option,
the query will instead be passed on down the plugin chain, which can include another plugin to handle
@@ -99,8 +105,6 @@ kubernetes [ZONES...] {
This allows the querying pod to continue searching for the service in the search path.
The search path could, for example, include another Kubernetes cluster.
-Enabling zone transfer is done by using the *transfer* plugin.
-
## Ready
This plugin reports readiness to the ready plugin. This will happen after it has synced to the
@@ -234,8 +238,3 @@ If monitoring is enabled (via the *prometheus* plugin) then the following metric
## Bugs
The duration metric only supports the "headless\_with\_selector" service currently.
-
-## Also See
-
-See the *autopath* plugin to enable search path optimizations. And use the *transfer* plugin to
-enable outgoing zone transfers.
diff --git a/plugin/kubernetes/handler.go b/plugin/kubernetes/handler.go
index 57e9ac528..78761d303 100644
--- a/plugin/kubernetes/handler.go
+++ b/plugin/kubernetes/handler.go
@@ -28,6 +28,8 @@ func (k Kubernetes) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.M
)
switch state.QType() {
+ case dns.TypeAXFR, dns.TypeIXFR:
+ k.Transfer(ctx, state)
case dns.TypeA:
records, err = plugin.A(ctx, &k, zone, state, nil, plugin.Options{})
case dns.TypeAAAA:
diff --git a/plugin/kubernetes/handler_test.go b/plugin/kubernetes/handler_test.go
index 12ebc2765..302136837 100644
--- a/plugin/kubernetes/handler_test.go
+++ b/plugin/kubernetes/handler_test.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"testing"
+ "time"
"github.com/coredns/coredns/plugin/kubernetes/object"
"github.com/coredns/coredns/plugin/pkg/dnstest"
@@ -524,7 +525,7 @@ func (APIConnServeTest) Run() {}
func (APIConnServeTest) Stop() error { return nil }
func (APIConnServeTest) EpIndexReverse(string) []*object.Endpoints { return nil }
func (APIConnServeTest) SvcIndexReverse(string) []*object.Service { return nil }
-func (APIConnServeTest) Modified() int64 { return int64(3) }
+func (APIConnServeTest) Modified() int64 { return time.Now().Unix() }
func (APIConnServeTest) PodIndex(ip string) []*object.Pod {
if ip != "10.240.0.1" {
diff --git a/plugin/kubernetes/kubernetes.go b/plugin/kubernetes/kubernetes.go
index 83b4b02d1..7805bff3d 100644
--- a/plugin/kubernetes/kubernetes.go
+++ b/plugin/kubernetes/kubernetes.go
@@ -46,6 +46,7 @@ type Kubernetes struct {
primaryZoneIndex int
localIPs []net.IP
autoPathSearch []string // Local search path from /etc/resolv.conf. Needed for autopath.
+ TransferTo []string
}
// New returns a initialized Kubernetes. It default interfaceAddrFunc to return 127.0.0.1. All other
@@ -494,12 +495,6 @@ func (k *Kubernetes) findServices(r recordRequest, zone string) (services []msg.
return services, err
}
-// Serial return the SOA serial.
-func (k *Kubernetes) Serial(state request.Request) uint32 { return uint32(k.APIConn.Modified()) }
-
-// MinTTL returns the minimal TTL.
-func (k *Kubernetes) MinTTL(state request.Request) uint32 { return k.ttl }
-
// match checks if a and b are equal taking wildcards into account.
func match(a, b string) bool {
if wildcard(a) {
diff --git a/plugin/kubernetes/setup.go b/plugin/kubernetes/setup.go
index 7cbfc34bd..0c46a3ab6 100644
--- a/plugin/kubernetes/setup.go
+++ b/plugin/kubernetes/setup.go
@@ -14,6 +14,7 @@ import (
"github.com/coredns/coredns/plugin/metrics"
"github.com/coredns/coredns/plugin/pkg/dnsutil"
clog "github.com/coredns/coredns/plugin/pkg/log"
+ "github.com/coredns/coredns/plugin/pkg/parse"
"github.com/coredns/coredns/plugin/pkg/upstream"
"github.com/caddyserver/caddy"
@@ -240,6 +241,15 @@ func ParseStanza(c *caddy.Controller) (*Kubernetes, error) {
return nil, c.Errf("ttl must be in range [0, 3600]: %d", t)
}
k8s.ttl = uint32(t)
+ case "transfer":
+ tos, froms, err := parse.Transfer(c, false)
+ if err != nil {
+ return nil, err
+ }
+ if len(froms) != 0 {
+ return nil, c.Errf("transfer from is not supported with this plugin")
+ }
+ k8s.TransferTo = tos
case "noendpoints":
if len(c.RemainingArgs()) != 0 {
return nil, c.ArgErr()
diff --git a/plugin/kubernetes/setup_transfer_test.go b/plugin/kubernetes/setup_transfer_test.go
new file mode 100644
index 000000000..fce4e10c5
--- /dev/null
+++ b/plugin/kubernetes/setup_transfer_test.go
@@ -0,0 +1,47 @@
+package kubernetes
+
+import (
+ "testing"
+
+ "github.com/caddyserver/caddy"
+)
+
+func TestKubernetesParseTransfer(t *testing.T) {
+ tests := []struct {
+ input string // Corefile data as string
+ expected string
+ shouldErr bool
+ }{
+ {`kubernetes cluster.local {
+ transfer to 1.2.3.4
+ }`, "1.2.3.4:53", false},
+ {`kubernetes cluster.local {
+ transfer to 1.2.3.4:53
+ }`, "1.2.3.4:53", false},
+ {`kubernetes cluster.local {
+ transfer to *
+ }`, "*", false},
+ {`kubernetes cluster.local {
+ transfer
+ }`, "", true},
+ }
+
+ for i, tc := range tests {
+ c := caddy.NewTestController("dns", tc.input)
+ k, err := kubernetesParse(c)
+ if err != nil && !tc.shouldErr {
+ t.Fatalf("Test %d: Expected no error, got %q", i, err)
+ }
+ if err == nil && tc.shouldErr {
+ t.Fatalf("Test %d: Expected error, got none", i)
+ }
+ if err != nil && tc.shouldErr {
+ // input should error
+ continue
+ }
+
+ if k.TransferTo[0] != tc.expected {
+ t.Errorf("Test %d: Expected Transfer To to be %s, got %s", i, tc.expected, k.TransferTo[0])
+ }
+ }
+}
diff --git a/plugin/kubernetes/xfr.go b/plugin/kubernetes/xfr.go
index 0392f0252..a3a0d4a4a 100644
--- a/plugin/kubernetes/xfr.go
+++ b/plugin/kubernetes/xfr.go
@@ -4,151 +4,207 @@ import (
"context"
"math"
"net"
- "sort"
"strings"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/etcd/msg"
- "github.com/coredns/coredns/plugin/transfer"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
api "k8s.io/api/core/v1"
)
-// Transfer implements the transfer.Transfer interface.
-func (k *Kubernetes) Transfer(zone string, serial uint32) (<-chan []dns.RR, error) {
- // state is not used here, hence the empty request.Request{]
- soa, err := plugin.SOA(context.TODO(), k, zone, request.Request{}, plugin.Options{})
+const transferLength = 2000
+
+// Serial implements the Transferer interface.
+func (k *Kubernetes) Serial(state request.Request) uint32 { return uint32(k.APIConn.Modified()) }
+
+// MinTTL implements the Transferer interface.
+func (k *Kubernetes) MinTTL(state request.Request) uint32 { return k.ttl }
+
+// Transfer implements the Transferer interface.
+func (k *Kubernetes) Transfer(ctx context.Context, state request.Request) (int, error) {
+
+ if !k.transferAllowed(state) {
+ return dns.RcodeRefused, nil
+ }
+
+ // Get all services.
+ rrs := make(chan dns.RR)
+ go k.transfer(rrs, state.Zone)
+
+ records := []dns.RR{}
+ for r := range rrs {
+ records = append(records, r)
+ }
+
+ if len(records) == 0 {
+ return dns.RcodeServerFailure, nil
+ }
+
+ ch := make(chan *dns.Envelope)
+ tr := new(dns.Transfer)
+
+ soa, err := plugin.SOA(ctx, k, state.Zone, state, plugin.Options{})
if err != nil {
- return nil, transfer.ErrNotAuthoritative
+ return dns.RcodeServerFailure, nil
}
- ch := make(chan []dns.RR)
+ records = append(soa, records...)
+ records = append(records, soa...)
+ go func(ch chan *dns.Envelope) {
+ j, l := 0, 0
+ log.Infof("Outgoing transfer of %d records of zone %s to %s started", len(records), state.Zone, state.IP())
+ for i, r := range records {
+ l += dns.Len(r)
+ if l > transferLength {
+ ch <- &dns.Envelope{RR: records[j:i]}
+ l = 0
+ j = i
+ }
+ }
+ if j < len(records) {
+ ch <- &dns.Envelope{RR: records[j:]}
+ }
+ close(ch)
+ }(ch)
- zonePath := msg.Path(zone, "coredns")
- serviceList := k.APIConn.ServiceList()
+ tr.Out(state.W, state.Req, ch)
+ // Defer closing to the client
+ state.W.Hijack()
+ return dns.RcodeSuccess, nil
+}
- go func() {
- // ixfr fallback
- if serial != 0 && soa[0].(*dns.SOA).Serial == serial {
- ch <- soa
- close(ch)
- return
+// transferAllowed checks if incoming request for transferring the zone is allowed according to the ACLs.
+// Note: This is copied from zone.transferAllowed, but should eventually be factored into a common transfer pkg.
+func (k *Kubernetes) transferAllowed(state request.Request) bool {
+ for _, t := range k.TransferTo {
+ if t == "*" {
+ return true
+ }
+ // If remote IP matches we accept.
+ remote := state.IP()
+ to, _, err := net.SplitHostPort(t)
+ if err != nil {
+ continue
}
- ch <- soa
+ if to == remote {
+ return true
+ }
+ }
+ return false
+}
- sort.Slice(serviceList, func(i, j int) bool {
- return serviceList[i].Name < serviceList[j].Name
- })
+func (k *Kubernetes) transfer(c chan dns.RR, zone string) {
- for _, svc := range serviceList {
- if !k.namespaceExposed(svc.Namespace) {
- continue
- }
- svcBase := []string{zonePath, Svc, svc.Namespace, svc.Name}
- switch svc.Type {
+ defer close(c)
- case api.ServiceTypeClusterIP, api.ServiceTypeNodePort, api.ServiceTypeLoadBalancer:
- clusterIP := net.ParseIP(svc.ClusterIP)
- if clusterIP != nil {
- s := msg.Service{Host: svc.ClusterIP, TTL: k.ttl}
+ zonePath := msg.Path(zone, "coredns")
+ serviceList := k.APIConn.ServiceList()
+ for _, svc := range serviceList {
+ if !k.namespaceExposed(svc.Namespace) {
+ continue
+ }
+ svcBase := []string{zonePath, Svc, svc.Namespace, svc.Name}
+ switch svc.Type {
+ case api.ServiceTypeClusterIP, api.ServiceTypeNodePort, api.ServiceTypeLoadBalancer:
+ clusterIP := net.ParseIP(svc.ClusterIP)
+ if clusterIP != nil {
+ s := msg.Service{Host: svc.ClusterIP, TTL: k.ttl}
+ s.Key = strings.Join(svcBase, "/")
+
+ // Change host from IP to Name for SRV records
+ host := emitAddressRecord(c, s)
+
+ for _, p := range svc.Ports {
+ s := msg.Service{Host: host, Port: int(p.Port), TTL: k.ttl}
s.Key = strings.Join(svcBase, "/")
- // Change host from IP to Name for SRV records
- host := emitAddressRecord(ch, s)
+ // Need to generate this to handle use cases for peer-finder
+ // ref: https://github.com/coredns/coredns/pull/823
+ c <- s.NewSRV(msg.Domain(s.Key), 100)
- for _, p := range svc.Ports {
- s := msg.Service{Host: host, Port: int(p.Port), TTL: k.ttl}
- s.Key = strings.Join(svcBase, "/")
+ // As per spec unnamed ports do not have a srv record
+ // https://github.com/kubernetes/dns/blob/master/docs/specification.md#232---srv-records
+ if p.Name == "" {
+ continue
+ }
- // Need to generate this to handle use cases for peer-finder
- // ref: https://github.com/coredns/coredns/pull/823
- ch <- []dns.RR{s.NewSRV(msg.Domain(s.Key), 100)}
+ s.Key = strings.Join(append(svcBase, strings.ToLower("_"+string(p.Protocol)), strings.ToLower("_"+string(p.Name))), "/")
- // As per spec unnamed ports do not have a srv record
- // https://github.com/kubernetes/dns/blob/master/docs/specification.md#232---srv-records
- if p.Name == "" {
- continue
- }
+ c <- s.NewSRV(msg.Domain(s.Key), 100)
+ }
- s.Key = strings.Join(append(svcBase, strings.ToLower("_"+string(p.Protocol)), strings.ToLower("_"+string(p.Name))), "/")
+ // Skip endpoint discovery if clusterIP is defined
+ continue
+ }
- ch <- []dns.RR{s.NewSRV(msg.Domain(s.Key), 100)}
- }
+ endpointsList := k.APIConn.EpIndex(svc.Name + "." + svc.Namespace)
- // Skip endpoint discovery if clusterIP is defined
+ for _, ep := range endpointsList {
+ if ep.Name != svc.Name || ep.Namespace != svc.Namespace {
continue
}
- endpointsList := k.APIConn.EpIndex(svc.Name + "." + svc.Namespace)
+ for _, eps := range ep.Subsets {
+ srvWeight := calcSRVWeight(len(eps.Addresses))
+ for _, addr := range eps.Addresses {
+ s := msg.Service{Host: addr.IP, TTL: k.ttl}
+ s.Key = strings.Join(svcBase, "/")
+ // We don't need to change the msg.Service host from IP to Name yet
+ // so disregard the return value here
+ emitAddressRecord(c, s)
+
+ s.Key = strings.Join(append(svcBase, endpointHostname(addr, k.endpointNameMode)), "/")
+ // Change host from IP to Name for SRV records
+ host := emitAddressRecord(c, s)
+ s.Host = host
+
+ for _, p := range eps.Ports {
+ // As per spec unnamed ports do not have a srv record
+ // https://github.com/kubernetes/dns/blob/master/docs/specification.md#232---srv-records
+ if p.Name == "" {
+ continue
+ }
- for _, ep := range endpointsList {
- if ep.Name != svc.Name || ep.Namespace != svc.Namespace {
- continue
- }
+ s.Port = int(p.Port)
- for _, eps := range ep.Subsets {
- srvWeight := calcSRVWeight(len(eps.Addresses))
- for _, addr := range eps.Addresses {
- s := msg.Service{Host: addr.IP, TTL: k.ttl}
- s.Key = strings.Join(svcBase, "/")
- // We don't need to change the msg.Service host from IP to Name yet
- // so disregard the return value here
- emitAddressRecord(ch, s)
-
- s.Key = strings.Join(append(svcBase, endpointHostname(addr, k.endpointNameMode)), "/")
- // Change host from IP to Name for SRV records
- host := emitAddressRecord(ch, s)
- s.Host = host
-
- for _, p := range eps.Ports {
- // As per spec unnamed ports do not have a srv record
- // https://github.com/kubernetes/dns/blob/master/docs/specification.md#232---srv-records
- if p.Name == "" {
- continue
- }
-
- s.Port = int(p.Port)
-
- s.Key = strings.Join(append(svcBase, strings.ToLower("_"+string(p.Protocol)), strings.ToLower("_"+string(p.Name))), "/")
- ch <- []dns.RR{s.NewSRV(msg.Domain(s.Key), srvWeight)}
- }
+ s.Key = strings.Join(append(svcBase, strings.ToLower("_"+string(p.Protocol)), strings.ToLower("_"+string(p.Name))), "/")
+ c <- s.NewSRV(msg.Domain(s.Key), srvWeight)
}
}
}
+ }
- case api.ServiceTypeExternalName:
+ case api.ServiceTypeExternalName:
- s := msg.Service{Key: strings.Join(svcBase, "/"), Host: svc.ExternalName, TTL: k.ttl}
- if t, _ := s.HostType(); t == dns.TypeCNAME {
- ch <- []dns.RR{s.NewCNAME(msg.Domain(s.Key), s.Host)}
- }
+ s := msg.Service{Key: strings.Join(svcBase, "/"), Host: svc.ExternalName, TTL: k.ttl}
+ if t, _ := s.HostType(); t == dns.TypeCNAME {
+ c <- s.NewCNAME(msg.Domain(s.Key), s.Host)
}
}
- ch <- soa
- close(ch)
- }()
- return ch, nil
+ }
}
-// emitAddressRecord generates a new A or AAAA record based on the msg.Service and writes it to a channel.
+// emitAddressRecord generates a new A or AAAA record based on the msg.Service and writes it to
+// a channel.
// emitAddressRecord returns the host name from the generated record.
-func emitAddressRecord(c chan<- []dns.RR, s msg.Service) string {
- ip := net.ParseIP(s.Host)
- dnsType, _ := s.HostType()
+func emitAddressRecord(c chan dns.RR, message msg.Service) string {
+ ip := net.ParseIP(message.Host)
+ var host string
+ dnsType, _ := message.HostType()
switch dnsType {
case dns.TypeA:
- r := s.NewA(msg.Domain(s.Key), ip)
- c <- []dns.RR{r}
- return r.Hdr.Name
+ arec := message.NewA(msg.Domain(message.Key), ip)
+ host = arec.Hdr.Name
+ c <- arec
case dns.TypeAAAA:
- r := s.NewAAAA(msg.Domain(s.Key), ip)
- c <- []dns.RR{r}
- return r.Hdr.Name
+ arec := message.NewAAAA(msg.Domain(message.Key), ip)
+ host = arec.Hdr.Name
+ c <- arec
}
- return ""
+ return host
}
// calcSrvWeight borrows the logic implemented in plugin.SRV for dynamically
diff --git a/plugin/kubernetes/xfr_test.go b/plugin/kubernetes/xfr_test.go
index b5f13ad6e..1ada4f7aa 100644
--- a/plugin/kubernetes/xfr_test.go
+++ b/plugin/kubernetes/xfr_test.go
@@ -1,126 +1,229 @@
package kubernetes
import (
+ "context"
"strings"
"testing"
+ "github.com/coredns/coredns/plugin/kubernetes/object"
+ "github.com/coredns/coredns/plugin/pkg/dnstest"
+ "github.com/coredns/coredns/plugin/test"
+
"github.com/miekg/dns"
)
-func TestKubernetesAXFR(t *testing.T) {
+func TestKubernetesXFR(t *testing.T) {
k := New([]string{"cluster.local."})
k.APIConn = &APIConnServeTest{}
+ k.TransferTo = []string{"10.240.0.1:53"}
k.Namespaces = map[string]struct{}{"testns": {}}
+ ctx := context.TODO()
+ w := dnstest.NewMultiRecorder(&test.ResponseWriter{})
dnsmsg := &dns.Msg{}
dnsmsg.SetAxfr(k.Zones[0])
- ch, err := k.Transfer(k.Zones[0], 0)
+ _, err := k.ServeDNS(ctx, w, dnsmsg)
if err != nil {
t.Error(err)
}
- validateAXFR(t, ch)
-}
-func TestKubernetesIXFRFallback(t *testing.T) {
- k := New([]string{"cluster.local."})
- k.APIConn = &APIConnServeTest{}
- k.Namespaces = map[string]struct{}{"testns": {}}
+ if len(w.Msgs) == 0 {
+ t.Logf("%+v\n", w)
+ t.Fatal("Did not get back a zone response")
+ }
- dnsmsg := &dns.Msg{}
- dnsmsg.SetAxfr(k.Zones[0])
+ if len(w.Msgs[0].Answer) == 0 {
+ t.Logf("%+v\n", w)
+ t.Fatal("Did not get back an answer")
+ }
+
+ // Ensure xfr starts with SOA
+ if w.Msgs[0].Answer[0].Header().Rrtype != dns.TypeSOA {
+ t.Error("Invalid XFR, does not start with SOA record")
+ }
+
+ // Ensure xfr starts with SOA
+ // Last message is empty, so we need to go back one further
+ if w.Msgs[len(w.Msgs)-2].Answer[len(w.Msgs[len(w.Msgs)-2].Answer)-1].Header().Rrtype != dns.TypeSOA {
+ t.Error("Invalid XFR, does not end with SOA record")
+ }
+
+ testRRs := []dns.RR{}
+ for _, tc := range dnsTestCases {
+ if tc.Rcode != dns.RcodeSuccess {
+ continue
+ }
+
+ for _, ans := range tc.Answer {
+ // Exclude wildcard searches
+ if strings.Contains(ans.Header().Name, "*") {
+ continue
+ }
+
+ // Exclude TXT records
+ if ans.Header().Rrtype == dns.TypeTXT {
+ continue
+ }
+ testRRs = append(testRRs, ans)
+ }
+ }
+
+ gotRRs := []dns.RR{}
+ for _, resp := range w.Msgs {
+ for _, ans := range resp.Answer {
+ // Skip SOA records since these
+ // test cases do not exist
+ if ans.Header().Rrtype == dns.TypeSOA {
+ continue
+ }
+
+ gotRRs = append(gotRRs, ans)
+ }
- ch, err := k.Transfer(k.Zones[0], 1)
- if err != nil {
- t.Error(err)
}
- validateAXFR(t, ch)
+
+ diff := difference(testRRs, gotRRs)
+ if len(diff) != 0 {
+ t.Errorf("Got back %d records that do not exist in test cases, should be 0:", len(diff))
+ for _, rec := range diff {
+ t.Errorf("%+v", rec)
+ }
+ }
+
+ diff = difference(gotRRs, testRRs)
+ if len(diff) != 0 {
+ t.Errorf("Found %d records we're missing, should be 0:", len(diff))
+ for _, rec := range diff {
+ t.Errorf("%+v", rec)
+ }
+ }
}
-func TestKubernetesIXFRCurrent(t *testing.T) {
+func TestKubernetesXFRNotAllowed(t *testing.T) {
k := New([]string{"cluster.local."})
k.APIConn = &APIConnServeTest{}
+ k.TransferTo = []string{"1.2.3.4:53"}
k.Namespaces = map[string]struct{}{"testns": {}}
+ ctx := context.TODO()
+ w := dnstest.NewMultiRecorder(&test.ResponseWriter{})
dnsmsg := &dns.Msg{}
dnsmsg.SetAxfr(k.Zones[0])
- ch, err := k.Transfer(k.Zones[0], 3)
+ _, err := k.ServeDNS(ctx, w, dnsmsg)
if err != nil {
t.Error(err)
}
- var gotRRs []dns.RR
- for rrs := range ch {
- gotRRs = append(gotRRs, rrs...)
+ if len(w.Msgs) == 0 {
+ t.Logf("%+v\n", w)
+ t.Fatal("Did not get back a zone response")
}
- // ensure only one record is returned
- if len(gotRRs) > 1 {
- t.Errorf("Expected only one answer, got %d", len(gotRRs))
+ if len(w.Msgs[0].Answer) != 0 {
+ t.Logf("%+v\n", w)
+ t.Fatal("Got an answer, should not have")
}
+}
- // Ensure first record is a SOA
- if gotRRs[0].Header().Rrtype != dns.TypeSOA {
- t.Error("Invalid transfer response, does not start with SOA record")
+// difference shows what we're missing when comparing two RR slices
+func difference(testRRs []dns.RR, gotRRs []dns.RR) []dns.RR {
+ expectedRRs := map[string]struct{}{}
+ for _, rr := range testRRs {
+ expectedRRs[rr.String()] = struct{}{}
}
+
+ foundRRs := []dns.RR{}
+ for _, rr := range gotRRs {
+ if _, ok := expectedRRs[rr.String()]; !ok {
+ foundRRs = append(foundRRs, rr)
+ }
+ }
+ return foundRRs
}
-func validateAXFR(t *testing.T, ch <-chan []dns.RR) {
- xfr := []dns.RR{}
- for rrs := range ch {
- xfr = append(xfr, rrs...)
+func TestEndpointsEquivalent(t *testing.T) {
+ epA := object.Endpoints{
+ Subsets: []object.EndpointSubset{{
+ Addresses: []object.EndpointAddress{{IP: "1.2.3.4", Hostname: "foo"}},
+ }},
+ }
+ epB := object.Endpoints{
+ Subsets: []object.EndpointSubset{{
+ Addresses: []object.EndpointAddress{{IP: "1.2.3.4", Hostname: "foo"}},
+ }},
}
- if xfr[0].Header().Rrtype != dns.TypeSOA {
- t.Error("Invalid transfer response, does not start with SOA record")
+ epC := object.Endpoints{
+ Subsets: []object.EndpointSubset{{
+ Addresses: []object.EndpointAddress{{IP: "1.2.3.5", Hostname: "foo"}},
+ }},
+ }
+ epD := object.Endpoints{
+ Subsets: []object.EndpointSubset{{
+ Addresses: []object.EndpointAddress{{IP: "1.2.3.5", Hostname: "foo"}},
+ },
+ {
+ Addresses: []object.EndpointAddress{{IP: "1.2.2.2", Hostname: "foofoo"}},
+ }},
+ }
+ epE := object.Endpoints{
+ Subsets: []object.EndpointSubset{{
+ Addresses: []object.EndpointAddress{{IP: "1.2.3.5", Hostname: "foo"}, {IP: "1.1.1.1"}},
+ }},
+ }
+ epF := object.Endpoints{
+ Subsets: []object.EndpointSubset{{
+ Addresses: []object.EndpointAddress{{IP: "1.2.3.4", Hostname: "foofoo"}},
+ }},
+ }
+ epG := object.Endpoints{
+ Subsets: []object.EndpointSubset{{
+ Addresses: []object.EndpointAddress{{IP: "1.2.3.4", Hostname: "foo"}},
+ Ports: []object.EndpointPort{{Name: "http", Port: 80, Protocol: "TCP"}},
+ }},
+ }
+ epH := object.Endpoints{
+ Subsets: []object.EndpointSubset{{
+ Addresses: []object.EndpointAddress{{IP: "1.2.3.4", Hostname: "foo"}},
+ Ports: []object.EndpointPort{{Name: "newportname", Port: 80, Protocol: "TCP"}},
+ }},
+ }
+ epI := object.Endpoints{
+ Subsets: []object.EndpointSubset{{
+ Addresses: []object.EndpointAddress{{IP: "1.2.3.4", Hostname: "foo"}},
+ Ports: []object.EndpointPort{{Name: "http", Port: 8080, Protocol: "TCP"}},
+ }},
+ }
+ epJ := object.Endpoints{
+ Subsets: []object.EndpointSubset{{
+ Addresses: []object.EndpointAddress{{IP: "1.2.3.4", Hostname: "foo"}},
+ Ports: []object.EndpointPort{{Name: "http", Port: 80, Protocol: "UDP"}},
+ }},
}
- zp := dns.NewZoneParser(strings.NewReader(expectedZone), "", "")
- i := 0
- for rr, ok := zp.Next(); ok; rr, ok = zp.Next() {
- if !dns.IsDuplicate(rr, xfr[i]) {
- t.Fatalf("Record %d, expected\n%v\n, got\n%v", i, rr, xfr[i])
- }
- i++
+ tests := []struct {
+ equiv bool
+ a *object.Endpoints
+ b *object.Endpoints
+ }{
+ {true, &epA, &epB},
+ {false, &epA, &epC},
+ {false, &epA, &epD},
+ {false, &epA, &epE},
+ {false, &epA, &epF},
+ {false, &epF, &epG},
+ {false, &epG, &epH},
+ {false, &epG, &epI},
+ {false, &epG, &epJ},
}
- if err := zp.Err(); err != nil {
- t.Fatal(err)
+ for i, tc := range tests {
+ if tc.equiv && !endpointsEquivalent(tc.a, tc.b) {
+ t.Errorf("Test %d: expected endpoints to be equivalent and they are not.", i)
+ }
+ if !tc.equiv && endpointsEquivalent(tc.a, tc.b) {
+ t.Errorf("Test %d: expected endpoints to be seen as different but they were not.", i)
+ }
}
}
-
-const expectedZone = `
-cluster.local. 5 IN SOA ns.dns.cluster.local. hostmaster.cluster.local. 3 7200 1800 86400 5
-external.testns.svc.cluster.local. 5 IN CNAME ext.interwebs.test.
-external-to-service.testns.svc.cluster.local. 5 IN CNAME svc1.testns.svc.cluster.local.
-hdls1.testns.svc.cluster.local. 5 IN A 172.0.0.2
-172-0-0-2.hdls1.testns.svc.cluster.local. 5 IN A 172.0.0.2
-_http._tcp.hdls1.testns.svc.cluster.local. 5 IN SRV 0 16 80 172-0-0-2.hdls1.testns.svc.cluster.local.
-hdls1.testns.svc.cluster.local. 5 IN A 172.0.0.3
-172-0-0-3.hdls1.testns.svc.cluster.local. 5 IN A 172.0.0.3
-_http._tcp.hdls1.testns.svc.cluster.local. 5 IN SRV 0 16 80 172-0-0-3.hdls1.testns.svc.cluster.local.
-hdls1.testns.svc.cluster.local. 5 IN A 172.0.0.4
-dup-name.hdls1.testns.svc.cluster.local. 5 IN A 172.0.0.4
-_http._tcp.hdls1.testns.svc.cluster.local. 5 IN SRV 0 16 80 dup-name.hdls1.testns.svc.cluster.local.
-hdls1.testns.svc.cluster.local. 5 IN A 172.0.0.5
-dup-name.hdls1.testns.svc.cluster.local. 5 IN A 172.0.0.5
-_http._tcp.hdls1.testns.svc.cluster.local. 5 IN SRV 0 16 80 dup-name.hdls1.testns.svc.cluster.local.
-hdls1.testns.svc.cluster.local. 5 IN AAAA 5678:abcd::1
-5678-abcd--1.hdls1.testns.svc.cluster.local. 5 IN AAAA 5678:abcd::1
-_http._tcp.hdls1.testns.svc.cluster.local. 5 IN SRV 0 16 80 5678-abcd--1.hdls1.testns.svc.cluster.local.
-hdls1.testns.svc.cluster.local. 5 IN AAAA 5678:abcd::2
-5678-abcd--2.hdls1.testns.svc.cluster.local. 5 IN AAAA 5678:abcd::2
-_http._tcp.hdls1.testns.svc.cluster.local. 5 IN SRV 0 16 80 5678-abcd--2.hdls1.testns.svc.cluster.local.
-hdlsprtls.testns.svc.cluster.local. 5 IN A 172.0.0.20
-172-0-0-20.hdlsprtls.testns.svc.cluster.local. 5 IN A 172.0.0.20
-svc1.testns.svc.cluster.local. 5 IN A 10.0.0.1
-svc1.testns.svc.cluster.local. 5 IN SRV 0 100 80 svc1.testns.svc.cluster.local.
-_http._tcp.svc1.testns.svc.cluster.local. 5 IN SRV 0 100 80 svc1.testns.svc.cluster.local.
-svc6.testns.svc.cluster.local. 5 IN AAAA 1234:abcd::1
-svc6.testns.svc.cluster.local. 5 IN SRV 0 100 80 svc6.testns.svc.cluster.local.
-_http._tcp.svc6.testns.svc.cluster.local. 5 IN SRV 0 100 80 svc6.testns.svc.cluster.local.
-svcempty.testns.svc.cluster.local. 5 IN A 10.0.0.1
-svcempty.testns.svc.cluster.local. 5 IN SRV 0 100 80 svcempty.testns.svc.cluster.local.
-_http._tcp.svcempty.testns.svc.cluster.local. 5 IN SRV 0 100 80 svcempty.testns.svc.cluster.local.
-cluster.local. 5 IN SOA ns.dns.cluster.local. hostmaster.cluster.local. 3 7200 1800 86400 5
-`
diff --git a/plugin/pkg/parse/parse.go b/plugin/pkg/parse/parse.go
index 75f60c05e..232e163fd 100644
--- a/plugin/pkg/parse/parse.go
+++ b/plugin/pkg/parse/parse.go
@@ -9,31 +9,41 @@ import (
"github.com/caddyserver/caddy"
)
-// TransferIn parses transfer statements: 'transfer from [address...]'.
-func TransferIn(c *caddy.Controller) (froms []string, err error) {
+// Transfer parses transfer statements: 'transfer [to|from] [address...]'.
+func Transfer(c *caddy.Controller, secondary bool) (tos, froms []string, err error) {
if !c.NextArg() {
- return nil, c.ArgErr()
+ return nil, nil, c.ArgErr()
}
value := c.Val()
switch value {
- default:
- return nil, c.Errf("unknown property %s", value)
+ case "to":
+ tos = c.RemainingArgs()
+ for i := range tos {
+ if tos[i] != "*" {
+ normalized, err := HostPort(tos[i], transport.Port)
+ if err != nil {
+ return nil, nil, err
+ }
+ tos[i] = normalized
+ }
+ }
+
case "from":
- froms = c.RemainingArgs()
- if len(froms) == 0 {
- return nil, c.ArgErr()
+ if !secondary {
+ return nil, nil, fmt.Errorf("can't use `transfer from` when not being a secondary")
}
+ froms = c.RemainingArgs()
for i := range froms {
if froms[i] != "*" {
normalized, err := HostPort(froms[i], transport.Port)
if err != nil {
- return nil, err
+ return nil, nil, err
}
froms[i] = normalized
} else {
- return nil, fmt.Errorf("can't use '*' in transfer from")
+ return nil, nil, fmt.Errorf("can't use '*' in transfer from")
}
}
}
- return froms, nil
+ return
}
diff --git a/plugin/pkg/parse/parse_test.go b/plugin/pkg/parse/parse_test.go
index b1a9f0282..a9f947a7d 100644
--- a/plugin/pkg/parse/parse_test.go
+++ b/plugin/pkg/parse/parse_test.go
@@ -6,41 +6,65 @@ import (
"github.com/caddyserver/caddy"
)
-func TestTransferIn(t *testing.T) {
+func TestTransfer(t *testing.T) {
tests := []struct {
inputFileRules string
shouldErr bool
+ secondary bool
+ expectedTo []string
expectedFrom []string
}{
+ // OK transfer to
+ {
+ `to 127.0.0.1`,
+ false, false, []string{"127.0.0.1:53"}, []string{},
+ },
+ // OK transfer tos
+ {
+ `to 127.0.0.1 127.0.0.2`,
+ false, false, []string{"127.0.0.1:53", "127.0.0.2:53"}, []string{},
+ },
+ // OK transfer from
{
`from 127.0.0.1`,
- false, []string{"127.0.0.1:53"},
+ false, true, []string{}, []string{"127.0.0.1:53"},
},
// OK transfer froms
{
`from 127.0.0.1 127.0.0.2`,
- false, []string{"127.0.0.1:53", "127.0.0.2:53"},
+ false, true, []string{}, []string{"127.0.0.1:53", "127.0.0.2:53"},
+ },
+ // OK transfer tos/froms
+ {
+ `to 127.0.0.1 127.0.0.2
+ from 127.0.0.1 127.0.0.2`,
+ false, true, []string{"127.0.0.1:53", "127.0.0.2:53"}, []string{"127.0.0.1:53", "127.0.0.2:53"},
+ },
+ // Bad transfer from, secondary false
+ {
+ `from 127.0.0.1`,
+ true, false, []string{}, []string{},
},
// Bad transfer from garbage
{
`from !@#$%^&*()`,
- true, []string{},
+ true, true, []string{}, []string{},
},
// Bad transfer from no args
{
`from`,
- true, []string{},
+ true, false, []string{}, []string{},
},
// Bad transfer from *
{
`from *`,
- true, []string{},
+ true, true, []string{}, []string{},
},
}
for i, test := range tests {
c := caddy.NewTestController("dns", test.inputFileRules)
- froms, err := TransferIn(c)
+ tos, froms, err := Transfer(c, test.secondary)
if err == nil && test.shouldErr {
t.Fatalf("Test %d expected errors, but got no error %+v %+v", i, err, test)
@@ -48,6 +72,13 @@ func TestTransferIn(t *testing.T) {
t.Fatalf("Test %d expected no errors, but got '%v'", i, err)
}
+ if test.expectedTo != nil {
+ for j, got := range tos {
+ if got != test.expectedTo[j] {
+ t.Fatalf("Test %d expected %v, got %v", i, test.expectedTo[j], got)
+ }
+ }
+ }
if test.expectedFrom != nil {
for j, got := range froms {
if got != test.expectedFrom[j] {
diff --git a/plugin/secondary/README.md b/plugin/secondary/README.md
index 1405627c0..dab740284 100644
--- a/plugin/secondary/README.md
+++ b/plugin/secondary/README.md
@@ -24,16 +24,17 @@ A working syntax would be:
~~~
secondary [zones...] {
transfer from ADDRESS
+ transfer to ADDRESS
}
~~~
* `transfer from` specifies from which address to fetch the zone. It can be specified multiple times;
- if one does not work, another will be tried. Transfering this zone outwards again can be done by
- enableing the *transfer* plugin.
+ if one does not work, another will be tried.
+* `transfer to` can be enabled to allow this secondary zone to be transferred again.
When a zone is due to be refreshed (Refresh timer fires) a random jitter of 5 seconds is
applied, before fetching. In the case of retry this will be 2 seconds. If there are any errors
-during the transfer in, the transfer fails; this will be logged.
+during the transfer the transfer fails; this will be logged.
## Examples
@@ -42,7 +43,8 @@ Transfer `example.org` from 10.0.1.1, and if that fails try 10.1.2.1.
~~~ corefile
example.org {
secondary {
- transfer from 10.0.1.1 10.1.2.1
+ transfer from 10.0.1.1
+ transfer from 10.1.2.1
}
}
~~~
@@ -50,12 +52,10 @@ example.org {
Or re-export the retrieved zone to other secondaries.
~~~ corefile
-example.net {
- secondary {
+. {
+ secondary example.net {
transfer from 10.1.2.1
- }
- transfer {
- to *
+ transfer to *
}
}
~~~
@@ -63,7 +63,3 @@ example.net {
## Bugs
Only AXFR is supported and the retrieved zone is not committed to disk.
-
-## Also See
-
-See the *transfer* plugin to enable zone transfers _to_ other servers.
diff --git a/plugin/secondary/setup.go b/plugin/secondary/setup.go
index 4bd43604c..410bc0976 100644
--- a/plugin/secondary/setup.go
+++ b/plugin/secondary/setup.go
@@ -44,6 +44,7 @@ func setup(c *caddy.Controller) error {
func secondaryParse(c *caddy.Controller) (file.Zones, error) {
z := make(map[string]*file.Zone)
names := []string{}
+ upstr := upstream.New()
for c.Next() {
if c.Val() == "secondary" {
@@ -62,24 +63,30 @@ func secondaryParse(c *caddy.Controller) (file.Zones, error) {
for c.NextBlock() {
- f := []string{}
+ t, f := []string{}, []string{}
+ var e error
switch c.Val() {
case "transfer":
- var err error
- f, err = parse.TransferIn(c)
- if err != nil {
- return file.Zones{}, err
+ t, f, e = parse.Transfer(c, true)
+ if e != nil {
+ return file.Zones{}, e
}
+ case "upstream":
+ // remove soon
+ c.RemainingArgs()
default:
return file.Zones{}, c.Errf("unknown property '%s'", c.Val())
}
for _, origin := range origins {
+ if t != nil {
+ z[origin].TransferTo = append(z[origin].TransferTo, t...)
+ }
if f != nil {
z[origin].TransferFrom = append(z[origin].TransferFrom, f...)
}
- z[origin].Upstream = upstream.New()
+ z[origin].Upstream = upstr
}
}
}
diff --git a/plugin/secondary/setup_test.go b/plugin/secondary/setup_test.go
index 11798ae43..7fc36f679 100644
--- a/plugin/secondary/setup_test.go
+++ b/plugin/secondary/setup_test.go
@@ -22,6 +22,7 @@ func TestSecondaryParse(t *testing.T) {
{
`secondary {
transfer from 127.0.0.1
+ transfer to 127.0.0.1
}`,
false,
"127.0.0.1:53",
@@ -30,6 +31,7 @@ func TestSecondaryParse(t *testing.T) {
{
`secondary example.org {
transfer from 127.0.0.1
+ transfer to 127.0.0.1
}`,
false,
"127.0.0.1:53",
diff --git a/plugin/transfer/README.md b/plugin/transfer/README.md
index 8924a1e79..30f797e5b 100644
--- a/plugin/transfer/README.md
+++ b/plugin/transfer/README.md
@@ -2,38 +2,34 @@
## Name
-*transfer* - perform (outgoing) zone transfers for other plugins.
+*transfer* - perform zone transfers for other plugins.
## Description
-This plugin answers zone transfers for authoritative plugins that implement `transfer.Transferer`.
+This plugin answers zone transfers for authoritative plugins that implement
+`transfer.Transferer`. Currently, no internal plugins implement this interface.
-*transfer* answers full zone transfer (AXFR) requests and incremental zone transfer (IXFR) requests
+Transfer answers full zone transfer (AXFR) requests and incremental zone transfer (IXFR) requests
with AXFR fallback if the zone has changed.
-When a plugin wants to notify it's secondaries it will call back into the *transfer* plugin.
-
-The following plugins implement zone transfers using this plugin: *file*, *auto*, *secondary*, and
-*kubernetes*. See `transfer.go` for implementation details if you are a plugin author that wants to
-use this plugin.
+Notifies are not currently supported.
## Syntax
~~~
transfer [ZONE...] {
- to ADDRESS...
+ to HOST...
}
~~~
- * **ZONE** The zones *transfer* will answer zone transfer requests for. If left blank, the zones
- are inherited from the enclosing server block. To answer zone transfers for a given zone,
- there must be another plugin in the same server block that serves the same zone, and implements
- `transfer.Transferer`.
+* **ZONES** The zones *transfer* will answer zone requests for. If left blank,
+ the zones are inherited from the enclosing server block. To answer zone
+ transfers for a given zone, there must be another plugin in the same server
+ block that serves the same zone, and implements `transfer.Transferer`.
- * `to` **ADDRESS...** The hosts *transfer* will transfer to. Use `*` to permit transfers to all
- addresses. **ADDRESS** must be denoted in CIDR notation (e.g., 127.0.0.1/32) or just as plain
- addresses. `to` may be specified multiple times.
+* `to ` **HOST...** The hosts *transfer* will transfer to. Use `*` to permit
+ transfers to all hosts.
## Examples
-See the specific plugins using this plugin for examples on it's usage.
+TODO
diff --git a/plugin/transfer/notify.go b/plugin/transfer/notify.go
deleted file mode 100644
index b024a3aa1..000000000
--- a/plugin/transfer/notify.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package transfer
-
-import (
- "fmt"
-
- "github.com/coredns/coredns/plugin/pkg/rcode"
-
- "github.com/miekg/dns"
-)
-
-// Notify will send notifies to all configured to hosts IP addresses. If the zone isn't known
-// to t an error will be returned. The string zone must be lowercased.
-func (t *Transfer) Notify(zone string) error {
- if t == nil { // t might be nil, mostly expected in tests, so intercept and to a noop in that case
- return nil
- }
-
- m := new(dns.Msg)
- m.SetNotify(zone)
- c := new(dns.Client)
-
- x := longestMatch(t.xfrs, zone)
- if x == nil {
- return fmt.Errorf("no such zone registred in the transfer plugin: %s", zone)
- }
-
- var err1 error
- for _, t := range x.to {
- if t == "*" {
- continue
- }
- if err := sendNotify(c, m, t); err != nil {
- err1 = err
- }
- }
- log.Debugf("Sent notifies for zone %q to %v", zone, x.to)
- return err1 // this only captures the last error
-}
-
-func sendNotify(c *dns.Client, m *dns.Msg, s string) error {
- var err error
-
- code := dns.RcodeServerFailure
- for i := 0; i < 3; i++ {
- ret, _, err := c.Exchange(m, s)
- if err != nil {
- continue
- }
- code = ret.Rcode
- if code == dns.RcodeSuccess {
- return nil
- }
- }
- if err != nil {
- return fmt.Errorf("notify for zone %q was not accepted by %q: %q", m.Question[0].Name, s, err)
- }
- return fmt.Errorf("notify for zone %q was not accepted by %q: rcode was %q", m.Question[0].Name, s, rcode.ToString(code))
-}
diff --git a/plugin/transfer/select_test.go b/plugin/transfer/select_test.go
deleted file mode 100644
index 6cb0d7681..000000000
--- a/plugin/transfer/select_test.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package transfer
-
-import (
- "context"
- "fmt"
- "testing"
-
- "github.com/coredns/coredns/plugin/pkg/dnstest"
- "github.com/coredns/coredns/plugin/test"
-
- "github.com/miekg/dns"
-)
-
-type (
- t1 struct{}
- t2 struct{}
-)
-
-func (t t1) Transfer(zone string, serial uint32) (<-chan []dns.RR, error) {
- const z = "example.org."
- if zone != z {
- return nil, ErrNotAuthoritative
- }
- return nil, fmt.Errorf(z)
-}
-func (t t2) Transfer(zone string, serial uint32) (<-chan []dns.RR, error) {
- const z = "sub.example.org."
- if zone != z {
- return nil, ErrNotAuthoritative
- }
- return nil, fmt.Errorf(z)
-}
-
-func TestZoneSelection(t *testing.T) {
- tr := &Transfer{
- Transferers: []Transferer{t1{}, t2{}},
- xfrs: []*xfr{
- {
- Zones: []string{"example.org."},
- to: []string{"192.0.2.1"}, // RFC 5737 IP, no interface should have this address.
- },
- {
- Zones: []string{"sub.example.org."},
- to: []string{"*"},
- },
- },
- }
- r := new(dns.Msg)
- r.SetAxfr("sub.example.org.")
- w := dnstest.NewRecorder(&test.ResponseWriter{})
- _, err := tr.ServeDNS(context.TODO(), w, r)
- if err == nil {
- t.Fatal("Expected error, got nil")
- }
- if x := err.Error(); x != "sub.example.org." {
- t.Errorf("Expected transfer for zone %s, got %s", "sub.example.org", x)
- }
-}
diff --git a/plugin/transfer/setup.go b/plugin/transfer/setup.go
index 66dd61fe9..f194bd2ec 100644
--- a/plugin/transfer/setup.go
+++ b/plugin/transfer/setup.go
@@ -3,7 +3,7 @@ package transfer
import (
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
- "github.com/coredns/coredns/plugin/pkg/parse"
+ parsepkg "github.com/coredns/coredns/plugin/pkg/parse"
"github.com/coredns/coredns/plugin/pkg/transport"
"github.com/caddyserver/caddy"
@@ -17,7 +17,7 @@ func init() {
}
func setup(c *caddy.Controller) error {
- t, err := parseTransfer(c)
+ t, err := parse(c)
if err != nil {
return plugin.Error("transfer", err)
@@ -44,7 +44,8 @@ func setup(c *caddy.Controller) error {
return nil
}
-func parseTransfer(c *caddy.Controller) (*Transfer, error) {
+func parse(c *caddy.Controller) (*Transfer, error) {
+
t := &Transfer{}
for c.Next() {
x := &xfr{}
@@ -82,14 +83,14 @@ func parseTransfer(c *caddy.Controller) (*Transfer, error) {
x.to = append(x.to, host)
continue
}
- normalized, err := parse.HostPort(host, transport.Port)
+ normalized, err := parsepkg.HostPort(host, transport.Port)
if err != nil {
return nil, err
}
x.to = append(x.to, normalized)
}
default:
- return nil, plugin.Error("transfer", c.Errf("unknown property %q", c.Val()))
+ return nil, plugin.Error("transfer", c.Errf("unknown property '%s'", c.Val()))
}
}
if len(x.to) == 0 {
diff --git a/plugin/transfer/setup_test.go b/plugin/transfer/setup_test.go
index aff6c7f44..09d8657e9 100644
--- a/plugin/transfer/setup_test.go
+++ b/plugin/transfer/setup_test.go
@@ -6,6 +6,12 @@ import (
"github.com/caddyserver/caddy"
)
+func newTestControllerWithZones(input string, zones []string) *caddy.Controller {
+ ctr := caddy.NewTestController("dns", input)
+ ctr.ServerBlockKeys = append(ctr.ServerBlockKeys, zones...)
+ return ctr
+}
+
func TestParse(t *testing.T) {
tests := []struct {
input string
@@ -69,10 +75,8 @@ func TestParse(t *testing.T) {
},
}
for i, tc := range tests {
- c := caddy.NewTestController("dns", tc.input)
- c.ServerBlockKeys = append(c.ServerBlockKeys, tc.zones...)
-
- transfer, err := parseTransfer(c)
+ c := newTestControllerWithZones(tc.input, tc.zones)
+ transfer, err := parse(c)
if err == nil && tc.shouldErr {
t.Fatalf("Test %d expected errors, but got no error", i)
diff --git a/plugin/transfer/transfer.go b/plugin/transfer/transfer.go
index 8008ddd1a..0bf92ac47 100644
--- a/plugin/transfer/transfer.go
+++ b/plugin/transfer/transfer.go
@@ -3,6 +3,7 @@ package transfer
import (
"context"
"errors"
+ "fmt"
"net"
"sync"
@@ -17,9 +18,9 @@ var log = clog.NewWithPlugin("transfer")
// Transfer is a plugin that handles zone transfers.
type Transfer struct {
- Transferers []Transferer // List of plugins that implement Transferer
+ Transferers []Transferer // the list of plugins that implement Transferer
xfrs []*xfr
- Next plugin.Handler
+ Next plugin.Handler // the next plugin in the chain
}
type xfr struct {
@@ -31,53 +32,53 @@ type xfr struct {
type Transferer interface {
// Transfer returns a channel to which it writes responses to the transfer request.
// If the plugin is not authoritative for the zone, it should immediately return the
- // transfer.ErrNotAuthoritative error. This is important otherwise the transfer plugin can
- // use plugin X while it should transfer the data from plugin Y.
+ // Transfer.ErrNotAuthoritative error.
//
// If serial is 0, handle as an AXFR request. Transfer should send all records
// in the zone to the channel. The SOA should be written to the channel first, followed
- // by all other records, including all NS + glue records. The implemenation is also responsible
- // for sending the last SOA record (to signal end of the transfer). This plugin will just grab
- // these records and send them back to the requester, there is little validation done.
+ // by all other records, including all NS + glue records.
//
- // If serial is not 0, it will be handled as an IXFR request. If the serial is equal to or greater (newer) than
- // the current serial for the zone, send a single SOA record to the channel and then close it.
+ // If serial is not 0, handle as an IXFR request. If the serial is equal to or greater (newer) than
+ // the current serial for the zone, send a single SOA record to the channel.
// If the serial is less (older) than the current serial for the zone, perform an AXFR fallback
// by proceeding as if an AXFR was requested (as above).
Transfer(zone string, serial uint32) (<-chan []dns.RR, error)
}
var (
- // ErrNotAuthoritative is returned by Transfer() when the plugin is not authoritative for the zone.
+ // ErrNotAuthoritative is returned by Transfer() when the plugin is not authoritative for the zone
ErrNotAuthoritative = errors.New("not authoritative for zone")
)
// ServeDNS implements the plugin.Handler interface.
-func (t *Transfer) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
+func (t Transfer) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := request.Request{W: w, Req: r}
if state.QType() != dns.TypeAXFR && state.QType() != dns.TypeIXFR {
return plugin.NextOrFailure(t.Name(), t.Next, ctx, w, r)
}
- x := longestMatch(t.xfrs, state.QName())
+ // Find the first transfer instance for which the queried zone is a subdomain.
+ var x *xfr
+ for _, xfr := range t.xfrs {
+ zone := plugin.Zones(xfr.Zones).Matches(state.Name())
+ if zone == "" {
+ continue
+ }
+ x = xfr
+ }
if x == nil {
+ // Requested zone did not match any transfer instance zones.
+ // Pass request down chain in case later plugins are capable of handling transfer requests themselves.
return plugin.NextOrFailure(t.Name(), t.Next, ctx, w, r)
}
if !x.allowed(state) {
- // write msg here, so logging will pick it up
- m := new(dns.Msg)
- m.SetRcode(r, dns.RcodeRefused)
- w.WriteMsg(m)
- return 0, nil
+ return dns.RcodeRefused, nil
}
- // Get serial from request if this is an IXFR.
+ // Get serial from request if this is an IXFR
var serial uint32
if state.QType() == dns.TypeIXFR {
- if len(r.Ns) != 1 {
- return dns.RcodeServerFailure, nil
- }
soa, ok := r.Ns[0].(*dns.SOA)
if !ok {
return dns.RcodeServerFailure, nil
@@ -85,11 +86,11 @@ func (t *Transfer) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Ms
serial = soa.Serial
}
- // Get a receiving channel from the first Transferer plugin that returns one.
- var pchan <-chan []dns.RR
- var err error
+ // Get a receiving channel from the first Transferer plugin that returns one
+ var fromPlugin <-chan []dns.RR
for _, p := range t.Transferers {
- pchan, err = p.Transfer(state.QName(), serial)
+ var err error
+ fromPlugin, err = p.Transfer(state.QName(), serial)
if err == ErrNotAuthoritative {
// plugin was not authoritative for the zone, try next plugin
continue
@@ -100,7 +101,7 @@ func (t *Transfer) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Ms
break
}
- if pchan == nil {
+ if fromPlugin == nil {
return plugin.NextOrFailure(t.Name(), t.Next, ctx, w, r)
}
@@ -114,51 +115,26 @@ func (t *Transfer) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Ms
wg.Done()
}()
+ var soa *dns.SOA
rrs := []dns.RR{}
l := 0
- var soa *dns.SOA
- for records := range pchan {
- if x, ok := records[0].(*dns.SOA); ok && soa == nil {
- soa = x
- }
- rrs = append(rrs, records...)
- if len(rrs) > 500 {
- ch <- &dns.Envelope{RR: rrs}
- l += len(rrs)
- rrs = []dns.RR{}
- }
- }
-
- // if we are here and we only hold 1 soa (len(rrs) == 1) and soa != nil, and IXFR fallback should
- // be performed. We haven't send anything on ch yet, so that can be closed (and waited for), and we only
- // need to return the SOA back to the client and return.
- if len(rrs) == 1 && soa != nil { // soa should never be nil...
- close(ch)
- wg.Wait()
-
- m := new(dns.Msg)
- m.SetReply(r)
- m.Answer = []dns.RR{soa}
- w.WriteMsg(m)
-
- log.Infof("Outgoing incremental transfer for up to date zone %q to %s for %d SOA serial", state.QName(), state.IP(), serial)
- return 0, nil
- }
-
- // if we are here and we only hold 1 soa (len(rrs) == 1) and soa != nil, and IXFR fallback should
- // be performed. We haven't send anything on ch yet, so that can be closed (and waited for), and we only
- // need to return the SOA back to the client and return.
- if len(rrs) == 1 && soa != nil { // soa should never be nil...
- close(ch)
- wg.Wait()
- m := new(dns.Msg)
- m.SetReply(r)
- m.Answer = []dns.RR{soa}
- w.WriteMsg(m)
-
- log.Infof("Outgoing noop, incremental transfer for up to date zone %q to %s for %d SOA serial", state.QName(), state.IP(), soa.Serial)
- return 0, nil
+receive:
+ for records := range fromPlugin {
+ for _, record := range records {
+ if soa == nil {
+ if soa = record.(*dns.SOA); soa == nil {
+ break receive
+ }
+ serial = soa.Serial
+ }
+ rrs = append(rrs, record)
+ if len(rrs) > 500 {
+ ch <- &dns.Envelope{RR: rrs}
+ l += len(rrs)
+ rrs = []dns.RR{}
+ }
+ }
}
if len(rrs) > 0 {
@@ -167,15 +143,20 @@ func (t *Transfer) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Ms
rrs = []dns.RR{}
}
+ if soa != nil {
+ ch <- &dns.Envelope{RR: []dns.RR{soa}} // closing SOA.
+ l++
+ }
+
close(ch) // Even though we close the channel here, we still have
wg.Wait() // to wait before we can return and close the connection.
- logserial := uint32(0)
- if soa != nil {
- logserial = soa.Serial
+ if soa == nil {
+ return dns.RcodeServerFailure, fmt.Errorf("first record in zone %s is not SOA", state.QName())
}
- log.Infof("Outgoing transfer of %d records of zone %q to %s for %d SOA serial", l, state.QName(), state.IP(), logserial)
- return 0, nil
+
+ log.Infof("Outgoing transfer of %d records of zone %s to %s with %d SOA serial", l, state.QName(), state.IP(), serial)
+ return dns.RcodeSuccess, nil
}
func (x xfr) allowed(state request.Request) bool {
@@ -187,30 +168,14 @@ func (x xfr) allowed(state request.Request) bool {
if err != nil {
return false
}
- // If remote IP matches we accept. TODO(): make this works with ranges
- if to == state.IP() {
+ // If remote IP matches we accept.
+ remote := state.IP()
+ if to == remote {
return true
}
}
return false
}
-// Find the first transfer instance for which the queried zone is the longest match. When nothing
-// is found nil is returned.
-func longestMatch(xfrs []*xfr, name string) *xfr {
- // TODO(xxx): optimize and make it a map (or maps)
- var x *xfr
- zone := "" // longest zone match wins
- for _, xfr := range xfrs {
- if z := plugin.Zones(xfr.Zones).Matches(name); z != "" {
- if z > zone {
- zone = z
- x = xfr
- }
- }
- }
- return x
-}
-
// Name implements the Handler interface.
func (Transfer) Name() string { return "transfer" }
diff --git a/plugin/transfer/transfer_test.go b/plugin/transfer/transfer_test.go
index c4b3891db..8dce4c6e1 100644
--- a/plugin/transfer/transfer_test.go
+++ b/plugin/transfer/transfer_test.go
@@ -12,18 +12,18 @@ import (
"github.com/miekg/dns"
)
-// transfererPlugin implements transfer.Transferer and plugin.Handler.
+// transfererPlugin implements transfer.Transferer and plugin.Handler
type transfererPlugin struct {
Zone string
Serial uint32
Next plugin.Handler
}
-// Name implements plugin.Handler.
-func (*transfererPlugin) Name() string { return "transfererplugin" }
+// Name implements plugin.Handler
+func (transfererPlugin) Name() string { return "transfererplugin" }
-// ServeDNS implements plugin.Handler.
-func (p *transfererPlugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
+// ServeDNS implements plugin.Handler
+func (p transfererPlugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
if r.Question[0].Name != p.Zone {
return p.Next.ServeDNS(ctx, w, r)
}
@@ -31,12 +31,12 @@ func (p *transfererPlugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r
}
// Transfer implements transfer.Transferer - it returns a static AXFR response, or
-// if serial is current, an abbreviated IXFR response.
-func (p *transfererPlugin) Transfer(zone string, serial uint32) (<-chan []dns.RR, error) {
+// if serial is current, an abbreviated IXFR response
+func (p transfererPlugin) Transfer(zone string, serial uint32) (<-chan []dns.RR, error) {
if zone != p.Zone {
return nil, ErrNotAuthoritative
}
- ch := make(chan []dns.RR, 3) // sending 3 bits and don't want to block, nor do a waitgroup
+ ch := make(chan []dns.RR, 2)
defer close(ch)
ch <- []dns.RR{test.SOA(fmt.Sprintf("%s 100 IN SOA ns.dns.%s hostmaster.%s %d 7200 1800 86400 100", p.Zone, p.Zone, p.Zone, p.Serial))}
if serial >= p.Serial {
@@ -46,31 +46,30 @@ func (p *transfererPlugin) Transfer(zone string, serial uint32) (<-chan []dns.RR
test.NS(fmt.Sprintf("%s 100 IN NS ns.dns.%s", p.Zone, p.Zone)),
test.A(fmt.Sprintf("ns.dns.%s 100 IN A 1.2.3.4", p.Zone)),
}
- ch <- []dns.RR{test.SOA(fmt.Sprintf("%s 100 IN SOA ns.dns.%s hostmaster.%s %d 7200 1800 86400 100", p.Zone, p.Zone, p.Zone, p.Serial))}
return ch, nil
}
type terminatingPlugin struct{}
-// Name implements plugin.Handler.
-func (*terminatingPlugin) Name() string { return "testplugin" }
+// Name implements plugin.Handler
+func (terminatingPlugin) Name() string { return "testplugin" }
-// ServeDNS implements plugin.Handler that returns NXDOMAIN for all requests.
-func (*terminatingPlugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
+// ServeDNS implements plugin.Handler that returns NXDOMAIN for all requests
+func (terminatingPlugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
m := new(dns.Msg)
m.SetRcode(r, dns.RcodeNameError)
w.WriteMsg(m)
return dns.RcodeNameError, nil
}
-func newTestTransfer() *Transfer {
+func newTestTransfer() Transfer {
nextPlugin1 := transfererPlugin{Zone: "example.com.", Serial: 12345}
nextPlugin2 := transfererPlugin{Zone: "example.org.", Serial: 12345}
- nextPlugin2.Next = &terminatingPlugin{}
- nextPlugin1.Next = &nextPlugin2
+ nextPlugin2.Next = terminatingPlugin{}
+ nextPlugin1.Next = nextPlugin2
- transfer := &Transfer{
- Transferers: []Transferer{&nextPlugin1, &nextPlugin2},
+ transfer := Transfer{
+ Transferers: []Transferer{nextPlugin1, nextPlugin2},
xfrs: []*xfr{
{
Zones: []string{"example.org."},
@@ -81,21 +80,22 @@ func newTestTransfer() *Transfer {
to: []string{"*"},
},
},
- Next: &nextPlugin1,
+ Next: nextPlugin1,
}
return transfer
}
func TestTransferNonZone(t *testing.T) {
+
transfer := newTestTransfer()
ctx := context.TODO()
for _, tc := range []string{"sub.example.org.", "example.test."} {
w := dnstest.NewRecorder(&test.ResponseWriter{})
- m := &dns.Msg{}
- m.SetAxfr(tc)
+ dnsmsg := &dns.Msg{}
+ dnsmsg.SetAxfr(tc)
- _, err := transfer.ServeDNS(ctx, w, m)
+ _, err := transfer.ServeDNS(ctx, w, dnsmsg)
if err != nil {
t.Error(err)
}
@@ -111,14 +111,15 @@ func TestTransferNonZone(t *testing.T) {
}
func TestTransferNotAXFRorIXFR(t *testing.T) {
+
transfer := newTestTransfer()
ctx := context.TODO()
w := dnstest.NewRecorder(&test.ResponseWriter{})
- m := &dns.Msg{}
- m.SetQuestion("test.domain.", dns.TypeA)
+ dnsmsg := &dns.Msg{}
+ dnsmsg.SetQuestion("test.domain.", dns.TypeA)
- _, err := transfer.ServeDNS(ctx, w, m)
+ _, err := transfer.ServeDNS(ctx, w, dnsmsg)
if err != nil {
t.Error(err)
}
@@ -133,14 +134,15 @@ func TestTransferNotAXFRorIXFR(t *testing.T) {
}
func TestTransferAXFRExampleOrg(t *testing.T) {
+
transfer := newTestTransfer()
ctx := context.TODO()
w := dnstest.NewMultiRecorder(&test.ResponseWriter{})
- m := &dns.Msg{}
- m.SetAxfr(transfer.xfrs[0].Zones[0])
+ dnsmsg := &dns.Msg{}
+ dnsmsg.SetAxfr(transfer.xfrs[0].Zones[0])
- _, err := transfer.ServeDNS(ctx, w, m)
+ _, err := transfer.ServeDNS(ctx, w, dnsmsg)
if err != nil {
t.Error(err)
}
@@ -149,14 +151,15 @@ func TestTransferAXFRExampleOrg(t *testing.T) {
}
func TestTransferAXFRExampleCom(t *testing.T) {
+
transfer := newTestTransfer()
ctx := context.TODO()
w := dnstest.NewMultiRecorder(&test.ResponseWriter{})
- m := &dns.Msg{}
- m.SetAxfr(transfer.xfrs[1].Zones[0])
+ dnsmsg := &dns.Msg{}
+ dnsmsg.SetAxfr(transfer.xfrs[1].Zones[0])
- _, err := transfer.ServeDNS(ctx, w, m)
+ _, err := transfer.ServeDNS(ctx, w, dnsmsg)
if err != nil {
t.Error(err)
}
@@ -164,61 +167,70 @@ func TestTransferAXFRExampleCom(t *testing.T) {
validateAXFRResponse(t, w)
}
-func TestTransferIXFRCurrent(t *testing.T) {
+func TestTransferIXFRFallback(t *testing.T) {
+
transfer := newTestTransfer()
- testPlugin := transfer.Transferers[0].(*transfererPlugin)
+ testPlugin := transfer.Transferers[0].(transfererPlugin)
ctx := context.TODO()
w := dnstest.NewMultiRecorder(&test.ResponseWriter{})
- m := &dns.Msg{}
- m.SetIxfr(transfer.xfrs[0].Zones[0], testPlugin.Serial, "ns.dns."+testPlugin.Zone, "hostmaster.dns."+testPlugin.Zone)
+ dnsmsg := &dns.Msg{}
+ dnsmsg.SetIxfr(
+ transfer.xfrs[0].Zones[0],
+ testPlugin.Serial-1,
+ "ns.dns."+testPlugin.Zone,
+ "hostmaster.dns."+testPlugin.Zone,
+ )
- _, err := transfer.ServeDNS(ctx, w, m)
+ _, err := transfer.ServeDNS(ctx, w, dnsmsg)
if err != nil {
t.Error(err)
}
- if len(w.Msgs) == 0 {
- t.Fatal("Did not get back a zone response")
- }
-
- if len(w.Msgs[0].Answer) != 1 {
- t.Logf("%+v\n", w)
- t.Fatalf("Expected 1 answer, got %d", len(w.Msgs[0].Answer))
- }
-
- // Ensure the answer is the SOA
- if w.Msgs[0].Answer[0].Header().Rrtype != dns.TypeSOA {
- t.Error("Answer does not contain the SOA record")
- }
+ validateAXFRResponse(t, w)
}
-func TestTransferIXFRFallback(t *testing.T) {
+func TestTransferIXFRCurrent(t *testing.T) {
+
transfer := newTestTransfer()
- testPlugin := transfer.Transferers[0].(*transfererPlugin)
+ testPlugin := transfer.Transferers[0].(transfererPlugin)
ctx := context.TODO()
w := dnstest.NewMultiRecorder(&test.ResponseWriter{})
- m := &dns.Msg{}
- m.SetIxfr(
+ dnsmsg := &dns.Msg{}
+ dnsmsg.SetIxfr(
transfer.xfrs[0].Zones[0],
- testPlugin.Serial-1,
+ testPlugin.Serial,
"ns.dns."+testPlugin.Zone,
"hostmaster.dns."+testPlugin.Zone,
)
- _, err := transfer.ServeDNS(ctx, w, m)
+ _, err := transfer.ServeDNS(ctx, w, dnsmsg)
if err != nil {
t.Error(err)
}
- validateAXFRResponse(t, w)
+ if len(w.Msgs) == 0 {
+ t.Logf("%+v\n", w)
+ t.Fatal("Did not get back a zone response")
+ }
+
+ if len(w.Msgs[0].Answer) != 1 {
+ t.Logf("%+v\n", w)
+ t.Fatalf("Expected 1 answer, got %d", len(w.Msgs[0].Answer))
+ }
+
+ // Ensure the answer is the SOA
+ if w.Msgs[0].Answer[0].Header().Rrtype != dns.TypeSOA {
+ t.Error("Answer does not contain the SOA record")
+ }
}
func validateAXFRResponse(t *testing.T, w *dnstest.MultiRecorder) {
if len(w.Msgs) == 0 {
+ t.Logf("%+v\n", w)
t.Fatal("Did not get back a zone response")
}
@@ -251,28 +263,29 @@ func TestTransferNotAllowed(t *testing.T) {
nextPlugin := transfererPlugin{Zone: "example.org.", Serial: 12345}
transfer := Transfer{
- Transferers: []Transferer{&nextPlugin},
+ Transferers: []Transferer{nextPlugin},
xfrs: []*xfr{
{
Zones: []string{"example.org."},
to: []string{"1.2.3.4"},
},
},
- Next: &nextPlugin,
+ Next: nextPlugin,
}
ctx := context.TODO()
- w := dnstest.NewRecorder(&test.ResponseWriter{})
- m := &dns.Msg{}
- m.SetAxfr(transfer.xfrs[0].Zones[0])
+ w := dnstest.NewMultiRecorder(&test.ResponseWriter{})
+ dnsmsg := &dns.Msg{}
+ dnsmsg.SetAxfr(transfer.xfrs[0].Zones[0])
- _, err := transfer.ServeDNS(ctx, w, m)
+ rcode, err := transfer.ServeDNS(ctx, w, dnsmsg)
if err != nil {
t.Error(err)
}
- if w.Msg.Rcode != dns.RcodeRefused {
- t.Errorf("Expected REFUSED response code, got %s", dns.RcodeToString[w.Msg.Rcode])
+ if rcode != dns.RcodeRefused {
+ t.Errorf("Expected REFUSED response code, got %s", dns.RcodeToString[rcode])
}
+
}