Commit 5301c5af authored by Miek Gieben's avatar Miek Gieben Committed by GitHub

Run golint and go vet (#276)

Cleanup the errors and removed deadcode along the way. The leaves
some error laying around, mostly about commenting exported identifier.
We should look hard if those really are needed.
parent 7b79458c
...@@ -56,7 +56,7 @@ func cacheParse(c *caddy.Controller) (int, []string, error) { ...@@ -56,7 +56,7 @@ func cacheParse(c *caddy.Controller) (int, []string, error) {
} }
} }
for i, _ := range origins { for i := range origins {
origins[i] = middleware.Host(origins[i]).Normalize() origins[i] = middleware.Host(origins[i]).Normalize()
} }
return ttl, origins, nil return ttl, origins, nil
......
...@@ -10,16 +10,16 @@ import ( ...@@ -10,16 +10,16 @@ import (
"github.com/miekg/dns" "github.com/miekg/dns"
) )
type DnssecResponseWriter struct { type ResponseWriter struct {
dns.ResponseWriter dns.ResponseWriter
d Dnssec d Dnssec
} }
func NewDnssecResponseWriter(w dns.ResponseWriter, d Dnssec) *DnssecResponseWriter { func NewDnssecResponseWriter(w dns.ResponseWriter, d Dnssec) *ResponseWriter {
return &DnssecResponseWriter{w, d} return &ResponseWriter{w, d}
} }
func (d *DnssecResponseWriter) WriteMsg(res *dns.Msg) error { func (d *ResponseWriter) WriteMsg(res *dns.Msg) error {
// By definition we should sign anything that comes back, we should still figure out for // By definition we should sign anything that comes back, we should still figure out for
// which zone it should be. // which zone it should be.
state := request.Request{W: d.ResponseWriter, Req: res} state := request.Request{W: d.ResponseWriter, Req: res}
...@@ -38,13 +38,13 @@ func (d *DnssecResponseWriter) WriteMsg(res *dns.Msg) error { ...@@ -38,13 +38,13 @@ func (d *DnssecResponseWriter) WriteMsg(res *dns.Msg) error {
return d.ResponseWriter.WriteMsg(res) return d.ResponseWriter.WriteMsg(res)
} }
func (d *DnssecResponseWriter) Write(buf []byte) (int, error) { func (d *ResponseWriter) Write(buf []byte) (int, error) {
log.Printf("[WARNING] Dnssec called with Write: not signing reply") log.Printf("[WARNING] Dnssec called with Write: not signing reply")
n, err := d.ResponseWriter.Write(buf) n, err := d.ResponseWriter.Write(buf)
return n, err return n, err
} }
func (d *DnssecResponseWriter) Hijack() { func (d *ResponseWriter) Hijack() {
d.ResponseWriter.Hijack() d.ResponseWriter.Hijack()
return return
} }
...@@ -39,7 +39,7 @@ func TestZoneReload(t *testing.T) { ...@@ -39,7 +39,7 @@ func TestZoneReload(t *testing.T) {
t.Fatalf("expected 5 RRs, got %d", len(z.All())) t.Fatalf("expected 5 RRs, got %d", len(z.All()))
} }
if err := ioutil.WriteFile(fileName, []byte(reloadZone2Test), 0644); err != nil { if err := ioutil.WriteFile(fileName, []byte(reloadZone2Test), 0644); err != nil {
t.Fatalf("failed to write new zone data", err) t.Fatalf("failed to write new zone data: %s", err)
} }
// Could still be racy, but we need to wait a bit for the event to be seen // Could still be racy, but we need to wait a bit for the event to be seen
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
......
...@@ -176,7 +176,6 @@ Restart: ...@@ -176,7 +176,6 @@ Restart:
} }
} }
} }
return nil
} }
// The maximum difference between two serial numbers. If the difference between // The maximum difference between two serial numbers. If the difference between
......
...@@ -39,7 +39,6 @@ func less(a, b string) int { ...@@ -39,7 +39,6 @@ func less(a, b string) int {
i++ i++
aj, bj = ai, bi aj, bj = ai, bi
} }
return 0
} }
func doDDD(b []byte) { func doDDD(b []byte) {
......
...@@ -107,7 +107,7 @@ func kubernetesParse(c *caddy.Controller) (Kubernetes, error) { ...@@ -107,7 +107,7 @@ func kubernetesParse(c *caddy.Controller) (Kubernetes, error) {
if len(args) != 0 { if len(args) != 0 {
k8s.ResyncPeriod, err = time.ParseDuration(args[0]) k8s.ResyncPeriod, err = time.ParseDuration(args[0])
if err != nil { if err != nil {
err = errors.New(fmt.Sprintf("Unable to parse resync duration value. Value provided was '%v'. Example valid values: '15s', '5m', '1h'. Error was: %v", args[0], err)) err = fmt.Errorf("Unable to parse resync duration value. Value provided was '%v'. Example valid values: '15s', '5m', '1h'. Error was: %v", args[0], err)
return Kubernetes{}, err return Kubernetes{}, err
} }
} else { } else {
...@@ -119,7 +119,7 @@ func kubernetesParse(c *caddy.Controller) (Kubernetes, error) { ...@@ -119,7 +119,7 @@ func kubernetesParse(c *caddy.Controller) (Kubernetes, error) {
labelSelectorString := strings.Join(args, " ") labelSelectorString := strings.Join(args, " ")
k8s.LabelSelector, err = unversionedapi.ParseToLabelSelector(labelSelectorString) k8s.LabelSelector, err = unversionedapi.ParseToLabelSelector(labelSelectorString)
if err != nil { if err != nil {
err = errors.New(fmt.Sprintf("Unable to parse label selector. Value provided was '%v'. Error was: %v", labelSelectorString, err)) err = fmt.Errorf("Unable to parse label selector. Value provided was '%v'. Error was: %v", labelSelectorString, err)
return Kubernetes{}, err return Kubernetes{}, err
} }
} else { } else {
......
...@@ -21,7 +21,7 @@ var examplesSubzoneConflict = map[string]bool{ ...@@ -21,7 +21,7 @@ var examplesSubzoneConflict = map[string]bool{
"": false, "": false,
} }
func TestsubzoneConflict(t *testing.T) { func TestSubzoneConflict(t *testing.T) {
for z, expected := range examplesSubzoneConflict { for z, expected := range examplesSubzoneConflict {
actual, conflicts := subzoneConflict(confZones, z) actual, conflicts := subzoneConflict(confZones, z)
......
...@@ -30,7 +30,7 @@ type Metrics struct { ...@@ -30,7 +30,7 @@ type Metrics struct {
Addr string Addr string
ln net.Listener ln net.Listener
mux *http.ServeMux mux *http.ServeMux
Once sync.Once Once *sync.Once
ZoneNames []string ZoneNames []string
} }
......
...@@ -47,7 +47,7 @@ func prometheusParse(c *caddy.Controller) (Metrics, error) { ...@@ -47,7 +47,7 @@ func prometheusParse(c *caddy.Controller) (Metrics, error) {
} }
met.ZoneNames = make([]string, len(c.ServerBlockKeys)) met.ZoneNames = make([]string, len(c.ServerBlockKeys))
copy(met.ZoneNames, c.ServerBlockKeys) copy(met.ZoneNames, c.ServerBlockKeys)
for i, _ := range met.ZoneNames { for i := range met.ZoneNames {
met.ZoneNames[i] = middleware.Host(met.ZoneNames[i]).Normalize() met.ZoneNames[i] = middleware.Host(met.ZoneNames[i]).Normalize()
} }
args := c.RemainingArgs() args := c.RemainingArgs()
...@@ -79,6 +79,6 @@ func prometheusParse(c *caddy.Controller) (Metrics, error) { ...@@ -79,6 +79,6 @@ func prometheusParse(c *caddy.Controller) (Metrics, error) {
return met, err return met, err
} }
var metricsOnce sync.Once var metricsOnce *sync.Once
const addr = "localhost:9153" const addr = "localhost:9153"
...@@ -7,6 +7,7 @@ import ( ...@@ -7,6 +7,7 @@ import (
"github.com/miekg/dns" "github.com/miekg/dns"
) )
// Zones respresents a lists of zone names.
type Zones []string type Zones []string
// Matches checks is qname is a subdomain of any of the zones in z. The match // Matches checks is qname is a subdomain of any of the zones in z. The match
...@@ -27,7 +28,7 @@ func (z Zones) Matches(qname string) string { ...@@ -27,7 +28,7 @@ func (z Zones) Matches(qname string) string {
// Normalize fully qualifies all zones in z. // Normalize fully qualifies all zones in z.
func (z Zones) Normalize() { func (z Zones) Normalize() {
for i, _ := range z { for i := range z {
z[i] = Name(z[i]).Normalize() z[i] = Name(z[i]).Normalize()
} }
} }
...@@ -47,10 +48,11 @@ func (n Name) Matches(child string) bool { ...@@ -47,10 +48,11 @@ func (n Name) Matches(child string) bool {
// Normalize lowercases and makes n fully qualified. // Normalize lowercases and makes n fully qualified.
func (n Name) Normalize() string { return strings.ToLower(dns.Fqdn(string(n))) } func (n Name) Normalize() string { return strings.ToLower(dns.Fqdn(string(n))) }
// Host represents a host from the Corefile, may contain port.
type ( type (
Host string // Host represents a host from the Corefile, may contain port.
Addr string Host string // Host represents a host from the Corefile, may contain port.
// Addr resprents an address in the Corefile.
Addr string // Addr resprents an address in the Corefile.
) )
// Normalize will return the host portion of host, stripping // Normalize will return the host portion of host, stripping
......
...@@ -6,6 +6,8 @@ import ( ...@@ -6,6 +6,8 @@ import (
"github.com/miekg/dns" "github.com/miekg/dns"
) )
// ToString convert the rcode to the offical DNS string, or to "RCODE"+value if the RCODE
// value is unknown.
func ToString(rcode int) string { func ToString(rcode int) string {
if str, ok := dns.RcodeToString[rcode]; ok { if str, ok := dns.RcodeToString[rcode]; ok {
return str return str
......
...@@ -2,14 +2,20 @@ package response ...@@ -2,14 +2,20 @@ package response
import "github.com/miekg/dns" import "github.com/miekg/dns"
// Type is the type of the message
type Type int type Type int
const ( const (
// Success indicates a positive reply
Success Type = iota Success Type = iota
NameError // NXDOMAIN in header, SOA in auth. // NameError is a NXDOMAIN in header, SOA in auth.
NoData // NOERROR in header, SOA in auth. NameError
Delegation // NOERROR in header, NS in auth, optionally fluff in additional (not checked). // NoData indicated name found, but not the type: NOERROR in header, SOA in auth.
OtherError // Don't cache these. NoData
// Delegation is a msg with a pointer to another nameserver: NOERROR in header, NS in auth, optionally fluff in additional (not checked).
Delegation
// OtherError indicated any other error: don't cache these.
OtherError
) )
// Classify classifies a message, it returns the Type. // Classify classifies a message, it returns the Type.
......
...@@ -25,7 +25,7 @@ type dir http.Dir ...@@ -25,7 +25,7 @@ type dir http.Dir
// //
// CoreDir will default to "$HOME/.coredns" on Unix, but it's location can be overriden with the COREDNSPATH // CoreDir will default to "$HOME/.coredns" on Unix, but it's location can be overriden with the COREDNSPATH
// environment variable. // environment variable.
var CoreDir dir = dir(fsPath()) var CoreDir = dir(fsPath())
func (d dir) Zone(z string) dir { func (d dir) Zone(z string) dir {
if z != "." && z[len(z)-2] == '.' { if z != "." && z[len(z)-2] == '.' {
......
...@@ -7,7 +7,7 @@ import ( ...@@ -7,7 +7,7 @@ import (
"testing" "testing"
) )
func TestfsPath(t *testing.T) { func TestFsPath(t *testing.T) {
if actual := fsPath(); !strings.HasSuffix(actual, ".coredns") { if actual := fsPath(); !strings.HasSuffix(actual, ".coredns") {
t.Errorf("Expected path to be a .coredns folder, got: %v", actual) t.Errorf("Expected path to be a .coredns folder, got: %v", actual)
} }
......
...@@ -13,13 +13,14 @@ type Handler struct { ...@@ -13,13 +13,14 @@ type Handler struct {
} }
func (h *Handler) Startup() error { func (h *Handler) Startup() error {
if ln, err := net.Listen("tcp", addr); err != nil { ln, err := net.Listen("tcp", addr)
if err != nil {
log.Printf("[ERROR] Failed to start pprof handler: %s", err) log.Printf("[ERROR] Failed to start pprof handler: %s", err)
return err return err
} else {
h.ln = ln
} }
h.ln = ln
h.mux = http.NewServeMux() h.mux = http.NewServeMux()
h.mux.HandleFunc(path+"/", pp.Index) h.mux.HandleFunc(path+"/", pp.Index)
h.mux.HandleFunc(path+"/cmdline", pp.Cmdline) h.mux.HandleFunc(path+"/cmdline", pp.Cmdline)
......
...@@ -56,7 +56,7 @@ func secondaryParse(c *caddy.Controller) (file.Zones, error) { ...@@ -56,7 +56,7 @@ func secondaryParse(c *caddy.Controller) (file.Zones, error) {
if len(args) > 0 { if len(args) > 0 {
origins = args origins = args
} }
for i, _ := range origins { for i := range origins {
origins[i] = middleware.Host(origins[i]).Normalize() origins[i] = middleware.Host(origins[i]).Normalize()
z[origins[i]] = file.NewZone(origins[i], "stdin") z[origins[i]] = file.NewZone(origins[i], "stdin")
names = append(names, origins[i]) names = append(names, origins[i])
......
...@@ -149,12 +149,12 @@ func Section(t *testing.T, tc Case, sect Sect, rr []dns.RR) bool { ...@@ -149,12 +149,12 @@ func Section(t *testing.T, tc Case, sect Sect, rr []dns.RR) bool {
return false return false
} }
if x.SignerName != section[i].(*dns.RRSIG).SignerName { if x.SignerName != section[i].(*dns.RRSIG).SignerName {
t.Errorf("rr %d should have a SignerName of %d, but has %d", i, section[i].(*dns.RRSIG).SignerName, x.SignerName) t.Errorf("rr %d should have a SignerName of %s, but has %s", i, section[i].(*dns.RRSIG).SignerName, x.SignerName)
return false return false
} }
case *dns.NSEC: case *dns.NSEC:
if x.NextDomain != section[i].(*dns.NSEC).NextDomain { if x.NextDomain != section[i].(*dns.NSEC).NextDomain {
t.Errorf("rr %d should have a NextDomain of %d, but has %d", i, section[i].(*dns.NSEC).NextDomain, x.NextDomain) t.Errorf("rr %d should have a NextDomain of %s, but has %s", i, section[i].(*dns.NSEC).NextDomain, x.NextDomain)
return false return false
} }
// TypeBitMap // TypeBitMap
......
...@@ -40,7 +40,7 @@ func (r *Request) IP() string { ...@@ -40,7 +40,7 @@ func (r *Request) IP() string {
return ip return ip
} }
// Post gets the (remote) Port of the client making the request. // Port gets the (remote) Port of the client making the request.
func (r *Request) Port() string { func (r *Request) Port() string {
_, port, err := net.SplitHostPort(r.W.RemoteAddr().String()) _, port, err := net.SplitHostPort(r.W.RemoteAddr().String())
if err != nil { if err != nil {
...@@ -57,9 +57,9 @@ func (r *Request) RemoteAddr() string { ...@@ -57,9 +57,9 @@ func (r *Request) RemoteAddr() string {
// Proto gets the protocol used as the transport. This will be udp or tcp. // Proto gets the protocol used as the transport. This will be udp or tcp.
func (r *Request) Proto() string { return Proto(r.W) } func (r *Request) Proto() string { return Proto(r.W) }
// FIXME(miek): why not a method on Request
// Proto gets the protocol used as the transport. This will be udp or tcp. // Proto gets the protocol used as the transport. This will be udp or tcp.
func Proto(w dns.ResponseWriter) string { func Proto(w dns.ResponseWriter) string {
// FIXME(miek): why not a method on Request
if _, ok := w.RemoteAddr().(*net.UDPAddr); ok { if _, ok := w.RemoteAddr().(*net.UDPAddr); ok {
return "udp" return "udp"
} }
......
package test
import (
"testing"
"github.com/miekg/dns"
"golang.org/x/net/context"
)
type Sect int
const (
Answer Sect = iota
Ns
Extra
)
type RRSet []dns.RR
func (p RRSet) Len() int { return len(p) }
func (p RRSet) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p RRSet) Less(i, j int) bool { return p[i].String() < p[j].String() }
// If the TTL of a record is 303 we don't care what the TTL is.
type Case struct {
Qname string
Qtype uint16
Rcode int
Do bool
Answer []dns.RR
Ns []dns.RR
Extra []dns.RR
}
func (c Case) Msg() *dns.Msg {
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(c.Qname), c.Qtype)
if c.Do {
o := new(dns.OPT)
o.Hdr.Name = "."
o.Hdr.Rrtype = dns.TypeOPT
o.SetDo()
o.SetUDPSize(4096)
m.Extra = []dns.RR{o}
}
return m
}
func A(rr string) *dns.A { r, _ := dns.NewRR(rr); return r.(*dns.A) }
func AAAA(rr string) *dns.AAAA { r, _ := dns.NewRR(rr); return r.(*dns.AAAA) }
func CNAME(rr string) *dns.CNAME { r, _ := dns.NewRR(rr); return r.(*dns.CNAME) }
func SRV(rr string) *dns.SRV { r, _ := dns.NewRR(rr); return r.(*dns.SRV) }
func SOA(rr string) *dns.SOA { r, _ := dns.NewRR(rr); return r.(*dns.SOA) }
func NS(rr string) *dns.NS { r, _ := dns.NewRR(rr); return r.(*dns.NS) }
func PTR(rr string) *dns.PTR { r, _ := dns.NewRR(rr); return r.(*dns.PTR) }
func TXT(rr string) *dns.TXT { r, _ := dns.NewRR(rr); return r.(*dns.TXT) }
func MX(rr string) *dns.MX { r, _ := dns.NewRR(rr); return r.(*dns.MX) }
func RRSIG(rr string) *dns.RRSIG { r, _ := dns.NewRR(rr); return r.(*dns.RRSIG) }
func NSEC(rr string) *dns.NSEC { r, _ := dns.NewRR(rr); return r.(*dns.NSEC) }
func DNSKEY(rr string) *dns.DNSKEY { r, _ := dns.NewRR(rr); return r.(*dns.DNSKEY) }
func OPT(bufsize int, do bool) *dns.OPT {
o := new(dns.OPT)
o.Hdr.Name = "."
o.Hdr.Rrtype = dns.TypeOPT
o.SetVersion(0)
o.SetUDPSize(uint16(bufsize))
if do {
o.SetDo()
}
return o
}
func Header(t *testing.T, tc Case, resp *dns.Msg) bool {
if resp.Rcode != tc.Rcode {
t.Errorf("rcode is %q, expected %q", dns.RcodeToString[resp.Rcode], dns.RcodeToString[tc.Rcode])
return false
}
if len(resp.Answer) != len(tc.Answer) {
t.Errorf("answer for %q contained %d results, %d expected", tc.Qname, len(resp.Answer), len(tc.Answer))
return false
}
if len(resp.Ns) != len(tc.Ns) {
t.Errorf("authority for %q contained %d results, %d expected", tc.Qname, len(resp.Ns), len(tc.Ns))
return false
}
if len(resp.Extra) != len(tc.Extra) {
t.Errorf("additional for %q contained %d results, %d expected", tc.Qname, len(resp.Extra), len(tc.Extra))
return false
}
return true
}
func Section(t *testing.T, tc Case, sect Sect, rr []dns.RR) bool {
section := []dns.RR{}
switch sect {
case 0:
section = tc.Answer
case 1:
section = tc.Ns
case 2:
section = tc.Extra
}
for i, a := range rr {
if a.Header().Name != section[i].Header().Name {
t.Errorf("rr %d should have a Header Name of %q, but has %q", i, section[i].Header().Name, a.Header().Name)
return false
}
// 303 signals: don't care what the ttl is.
if section[i].Header().Ttl != 303 && a.Header().Ttl != section[i].Header().Ttl {
if _, ok := section[i].(*dns.OPT); !ok {
// we check edns0 bufize on this one
t.Errorf("rr %d should have a Header TTL of %d, but has %d", i, section[i].Header().Ttl, a.Header().Ttl)
return false
}
}
if a.Header().Rrtype != section[i].Header().Rrtype {
t.Errorf("rr %d should have a header rr type of %d, but has %d", i, section[i].Header().Rrtype, a.Header().Rrtype)
return false
}
switch x := a.(type) {
case *dns.SRV:
if x.Priority != section[i].(*dns.SRV).Priority {
t.Errorf("rr %d should have a Priority of %d, but has %d", i, section[i].(*dns.SRV).Priority, x.Priority)
return false
}
if x.Weight != section[i].(*dns.SRV).Weight {
t.Errorf("rr %d should have a Weight of %d, but has %d", i, section[i].(*dns.SRV).Weight, x.Weight)
return false
}
if x.Port != section[i].(*dns.SRV).Port {
t.Errorf("rr %d should have a Port of %d, but has %d", i, section[i].(*dns.SRV).Port, x.Port)
return false
}
if x.Target != section[i].(*dns.SRV).Target {
t.Errorf("rr %d should have a Target of %q, but has %q", i, section[i].(*dns.SRV).Target, x.Target)
return false
}
case *dns.RRSIG:
if x.TypeCovered != section[i].(*dns.RRSIG).TypeCovered {
t.Errorf("rr %d should have a TypeCovered of %d, but has %d", i, section[i].(*dns.RRSIG).TypeCovered, x.TypeCovered)
return false
}
if x.Labels != section[i].(*dns.RRSIG).Labels {
t.Errorf("rr %d should have a Labels of %d, but has %d", i, section[i].(*dns.RRSIG).Labels, x.Labels)
return false
}
if x.SignerName != section[i].(*dns.RRSIG).SignerName {
t.Errorf("rr %d should have a SignerName of %d, but has %d", i, section[i].(*dns.RRSIG).SignerName, x.SignerName)
return false
}
case *dns.NSEC:
if x.NextDomain != section[i].(*dns.NSEC).NextDomain {
t.Errorf("rr %d should have a NextDomain of %d, but has %d", i, section[i].(*dns.NSEC).NextDomain, x.NextDomain)
return false
}
// TypeBitMap
case *dns.A:
if x.A.String() != section[i].(*dns.A).A.String() {
t.Errorf("rr %d should have a Address of %q, but has %q", i, section[i].(*dns.A).A.String(), x.A.String())
return false
}
case *dns.AAAA:
if x.AAAA.String() != section[i].(*dns.AAAA).AAAA.String() {
t.Errorf("rr %d should have a Address of %q, but has %q", i, section[i].(*dns.AAAA).AAAA.String(), x.AAAA.String())
return false
}
case *dns.TXT:
for j, txt := range x.Txt {
if txt != section[i].(*dns.TXT).Txt[j] {
t.Errorf("rr %d should have a Txt of %q, but has %q", i, section[i].(*dns.TXT).Txt[j], txt)
return false
}
}
case *dns.SOA:
tt := section[i].(*dns.SOA)
if x.Ns != tt.Ns {
t.Errorf("SOA nameserver should be %q, but is %q", x.Ns, tt.Ns)
return false
}
case *dns.PTR:
tt := section[i].(*dns.PTR)
if x.Ptr != tt.Ptr {
t.Errorf("PTR ptr should be %q, but is %q", x.Ptr, tt.Ptr)
return false
}
case *dns.CNAME:
tt := section[i].(*dns.CNAME)
if x.Target != tt.Target {
t.Errorf("CNAME target should be %q, but is %q", x.Target, tt.Target)
return false
}
case *dns.MX:
tt := section[i].(*dns.MX)
if x.Mx != tt.Mx {
t.Errorf("MX Mx should be %q, but is %q", x.Mx, tt.Mx)
return false
}
if x.Preference != tt.Preference {
t.Errorf("MX Preference should be %q, but is %q", x.Preference, tt.Preference)
return false
}
case *dns.NS:
tt := section[i].(*dns.NS)
if x.Ns != tt.Ns {
t.Errorf("NS nameserver should be %q, but is %q", x.Ns, tt.Ns)
return false
}
case *dns.OPT:
tt := section[i].(*dns.OPT)
if x.UDPSize() != tt.UDPSize() {
t.Errorf("OPT UDPSize should be %d, but is %d", tt.UDPSize(), x.UDPSize())
return false
}
if x.Do() != tt.Do() {
t.Errorf("OPT DO should be %t, but is %t", tt.Do(), x.Do())
return false
}
}
}
return true
}
func ErrorHandler() Handler {
return HandlerFunc(func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
m := new(dns.Msg)
m.SetRcode(r, dns.RcodeServerFailure)
w.WriteMsg(m)
return dns.RcodeServerFailure, nil
})
}
// Copied here to prevent an import cycle.
type (
// HandlerFunc is a convenience type like dns.HandlerFunc, except
// ServeDNS returns an rcode and an error.
HandlerFunc func(context.Context, dns.ResponseWriter, *dns.Msg) (int, error)
Handler interface {
ServeDNS(context.Context, dns.ResponseWriter, *dns.Msg) (int, error)
}
)
// ServeDNS implements the Handler interface.
func (f HandlerFunc) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
return f(ctx, w, r)
}
package test
import "testing"
func TestA(t *testing.T) { A("miek.nl. IN A 127.0.0.1") } // should not crash
...@@ -59,6 +59,6 @@ func TestLookupProxy(t *testing.T) { ...@@ -59,6 +59,6 @@ func TestLookupProxy(t *testing.T) {
t.Errorf("Expected RR to A, got: %d", resp.Answer[0].Header().Rrtype) t.Errorf("Expected RR to A, got: %d", resp.Answer[0].Header().Rrtype)
} }
if resp.Answer[0].(*dns.A).A.String() != "127.0.0.1" { if resp.Answer[0].(*dns.A).A.String() != "127.0.0.1" {
t.Errorf("Expected 127.0.0.1, got: %d", resp.Answer[0].(*dns.A).A.String()) t.Errorf("Expected 127.0.0.1, got: %s", resp.Answer[0].(*dns.A).A.String())
} }
} }
package test
import (
"net"
"github.com/miekg/dns"
)
type ResponseWriter struct{}
func (t *ResponseWriter) LocalAddr() net.Addr {
ip := net.ParseIP("127.0.0.1")
port := 53
return &net.UDPAddr{IP: ip, Port: port, Zone: ""}
}
func (t *ResponseWriter) RemoteAddr() net.Addr {
ip := net.ParseIP("10.240.0.1")
port := 40212
return &net.UDPAddr{IP: ip, Port: port, Zone: ""}
}
func (t *ResponseWriter) WriteMsg(m *dns.Msg) error { return nil }
func (t *ResponseWriter) Write(buf []byte) (int, error) { return len(buf), nil }
func (t *ResponseWriter) Close() error { return nil }
func (t *ResponseWriter) TsigStatus() error { return nil }
func (t *ResponseWriter) TsigTimersOnly(bool) { return }
func (t *ResponseWriter) Hijack() { return }
package test package test
import ( import (
"net" // Hook in CoreDNS.
"sync"
"testing"
"time"
_ "github.com/miekg/coredns/core" _ "github.com/miekg/coredns/core"
"github.com/mholt/caddy" "github.com/mholt/caddy"
"github.com/miekg/dns"
) )
// TCPServer returns a generic DNS server listening for TCP connections on laddr.
func TCPServer(t *testing.T, laddr string) (*dns.Server, string, error) {
l, err := net.Listen("tcp", laddr)
if err != nil {
return nil, "", err
}
server := &dns.Server{Listener: l, ReadTimeout: time.Hour, WriteTimeout: time.Hour}
waitLock := sync.Mutex{}
waitLock.Lock()
server.NotifyStartedFunc = func() { t.Logf("started TCP server on %s", l.Addr()); waitLock.Unlock() }
go func() {
server.ActivateAndServe()
l.Close()
}()
waitLock.Lock()
return server, l.Addr().String(), nil
}
// UDPServer returns a generic DNS server listening for UDP connections on laddr.
func UDPServer(t *testing.T, laddr string) (*dns.Server, string, error) {
pc, err := net.ListenPacket("udp", laddr)
if err != nil {
return nil, "", err
}
server := &dns.Server{PacketConn: pc, ReadTimeout: time.Hour, WriteTimeout: time.Hour}
waitLock := sync.Mutex{}
waitLock.Lock()
server.NotifyStartedFunc = func() { t.Logf("started UDP server on %s", pc.LocalAddr()); waitLock.Unlock() }
go func() {
server.ActivateAndServe()
pc.Close()
}()
waitLock.Lock()
return server, pc.LocalAddr().String(), nil
}
// CoreDNSServer returns a CoreDNS test server. It just takes a normal Corefile as input. // CoreDNSServer returns a CoreDNS test server. It just takes a normal Corefile as input.
func CoreDNSServer(corefile string) (*caddy.Instance, error) { func CoreDNSServer(corefile string) (*caddy.Instance, error) {
caddy.Quiet = true caddy.Quiet = true
return caddy.Start(NewInput(corefile)) return caddy.Start(NewInput(corefile))
} }
// CoreDNSSserverStop stops a server. // CoreDNSServerStop stops a server.
func CoreDNSServerStop(i *caddy.Instance) { i.Stop() } func CoreDNSServerStop(i *caddy.Instance) { i.Stop() }
// CoreDNSServeRPorts returns the ports the instance is listening on. The integer k indicates // CoreDNSServerPorts returns the ports the instance is listening on. The integer k indicates
// which ServerListener you want. // which ServerListener you want.
func CoreDNSServerPorts(i *caddy.Instance, k int) (udp, tcp string) { func CoreDNSServerPorts(i *caddy.Instance, k int) (udp, tcp string) {
srvs := i.Servers() srvs := i.Servers()
...@@ -83,14 +35,21 @@ func CoreDNSServerPorts(i *caddy.Instance, k int) (udp, tcp string) { ...@@ -83,14 +35,21 @@ func CoreDNSServerPorts(i *caddy.Instance, k int) (udp, tcp string) {
return return
} }
// Input implements the caddy.Input interface and acts as an easy way to use a string as a Corefile.
type Input struct { type Input struct {
corefile []byte corefile []byte
} }
// NewInput returns a pointer to Input, containing the corefile string as input.
func NewInput(corefile string) *Input { func NewInput(corefile string) *Input {
return &Input{corefile: []byte(corefile)} return &Input{corefile: []byte(corefile)}
} }
// Body implements the Input interface.
func (i *Input) Body() []byte { return i.corefile } func (i *Input) Body() []byte { return i.corefile }
// Path implements the Input interface.
func (i *Input) Path() string { return "Corefile" } func (i *Input) Path() string { return "Corefile" }
// ServerType implements the Input interface.
func (i *Input) ServerType() string { return "dns" } func (i *Input) ServerType() string { return "dns" }
...@@ -40,8 +40,9 @@ func TestProxyToChaosServer(t *testing.T) { ...@@ -40,8 +40,9 @@ func TestProxyToChaosServer(t *testing.T) {
} }
func chaosTest(t *testing.T, server string) { func chaosTest(t *testing.T, server string) {
m := Msg("version.bind.", dns.TypeTXT, nil) m := new(dns.Msg)
m.Question[0].Qclass = dns.ClassCHAOS m.Question = make([]dns.Question, 1)
m.Question[0] = dns.Question{Qclass: dns.ClassCHAOS, Name: "version.bind.", Qtype: dns.TypeTXT}
r, err := dns.Exchange(m, server) r, err := dns.Exchange(m, server)
if err != nil { if err != nil {
......
package test
import "github.com/miekg/dns"
func Msg(zone string, typ uint16, o *dns.OPT) *dns.Msg {
m := new(dns.Msg)
m.SetQuestion(zone, typ)
if o != nil {
m.Extra = []dns.RR{o}
}
return m
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment