plugin/rewrite: use request.Request and other cleanups (#1920)

This was done anyway, but only deep in the functions, just do this
everywhere; allows for shorter code and request.Request allows for
caching as well.

Cleanups, make it more Go like.
* remove unneeded switches
* remove testdir (why was this there??)
* simplify the logic
* remove unneeded variables
* put short functions on a single line
* fix documentation.
* spin off wire funcs in wire.go, make them functions.

Signed-off-by: Miek Gieben <miek@miek.nl>
This commit is contained in:
Miek Gieben
2018-07-02 15:39:50 +01:00
committed by Yong Tang
parent 1abecf99d9
commit 6dd2cf8c4b
12 changed files with 200 additions and 311 deletions

View File

@@ -4,6 +4,8 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/coredns/coredns/request"
"github.com/miekg/dns" "github.com/miekg/dns"
) )
@@ -27,22 +29,18 @@ func newClassRule(nextAction string, args ...string) (Rule, error) {
} }
// Rewrite rewrites the the current request. // Rewrite rewrites the the current request.
func (rule *classRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { func (rule *classRule) Rewrite(state request.Request) Result {
if rule.fromClass > 0 && rule.toClass > 0 { if rule.fromClass > 0 && rule.toClass > 0 {
if r.Question[0].Qclass == rule.fromClass { if state.Req.Question[0].Qclass == rule.fromClass {
r.Question[0].Qclass = rule.toClass state.Req.Question[0].Qclass = rule.toClass
return RewriteDone return RewriteDone
} }
} }
return RewriteIgnored return RewriteIgnored
} }
// Mode returns the processing mode // Mode returns the processing mode.
func (rule *classRule) Mode() string { func (rule *classRule) Mode() string { return rule.NextAction }
return rule.NextAction
}
// GetResponseRule return a rule to rewrite the response with. Currently not implemented. // GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *classRule) GetResponseRule() ResponseRule { func (rule *classRule) GetResponseRule() ResponseRule { return ResponseRule{} }
return ResponseRule{}
}

View File

@@ -10,7 +10,7 @@ import (
"github.com/miekg/dns" "github.com/miekg/dns"
) )
// Operators // Operators that are defined.
const ( const (
Is = "is" Is = "is"
Not = "not" Not = "not"
@@ -22,13 +22,7 @@ const (
NotMatch = "not_match" NotMatch = "not_match"
) )
func operatorError(operator string) error { func newReplacer(r *dns.Msg) replacer.Replacer { return replacer.New(r, nil, "") }
return fmt.Errorf("invalid operator %v", operator)
}
func newReplacer(r *dns.Msg) replacer.Replacer {
return replacer.New(r, nil, "")
}
// condition is a rewrite condition. // condition is a rewrite condition.
type condition func(string, string) bool type condition func(string, string) bool
@@ -44,53 +38,35 @@ var conditions = map[string]condition{
NotMatch: notMatchFunc, NotMatch: notMatchFunc,
} }
// isFunc is condition for Is operator. // isFunc is condition for Is operator. It checks for equality.
// It checks for equality. func isFunc(a, b string) bool { return a == b }
func isFunc(a, b string) bool {
return a == b
}
// notFunc is condition for Not operator. // notFunc is condition for Not operator. It checks for inequality.
// It checks for inequality. func notFunc(a, b string) bool { return a != b }
func notFunc(a, b string) bool {
return a != b
}
// hasFunc is condition for Has operator. // hasFunc is condition for Has operator. It checks if b is a substring of a.
// It checks if b is a substring of a. func hasFunc(a, b string) bool { return strings.Contains(a, b) }
func hasFunc(a, b string) bool {
return strings.Contains(a, b)
}
// notHasFunc is condition for NotHas operator. // notHasFunc is condition for NotHas operator. It checks if b is not a substring of a.
// It checks if b is not a substring of a. func notHasFunc(a, b string) bool { return !strings.Contains(a, b) }
func notHasFunc(a, b string) bool {
return !strings.Contains(a, b)
}
// startsWithFunc is condition for StartsWith operator. // startsWithFunc is condition for StartsWith operator. It checks if b is a prefix of a.
// It checks if b is a prefix of a. func startsWithFunc(a, b string) bool { return strings.HasPrefix(a, b) }
func startsWithFunc(a, b string) bool {
return strings.HasPrefix(a, b)
}
// endsWithFunc is condition for EndsWith operator. // endsWithFunc is condition for EndsWith operator. It checks if b is a suffix of a.
// It checks if b is a suffix of a.
func endsWithFunc(a, b string) bool { func endsWithFunc(a, b string) bool {
// TODO(miek): IsSubDomain // TODO(miek): IsSubDomain
return strings.HasSuffix(a, b) return strings.HasSuffix(a, b)
} }
// matchFunc is condition for Match operator. // matchFunc is condition for Match operator. It does regexp matching of a against pattern in b
// It does regexp matching of a against pattern in b
// and returns if they match. // and returns if they match.
func matchFunc(a, b string) bool { func matchFunc(a, b string) bool {
matched, _ := regexp.MatchString(b, a) matched, _ := regexp.MatchString(b, a)
return matched return matched
} }
// notMatchFunc is condition for NotMatch operator. // notMatchFunc is condition for NotMatch operator. It does regexp matching of a against pattern in b
// It does regexp matching of a against pattern in b
// and returns if they do not match. // and returns if they do not match.
func notMatchFunc(a, b string) bool { func notMatchFunc(a, b string) bool {
matched, _ := regexp.MatchString(b, a) matched, _ := regexp.MatchString(b, a)
@@ -122,7 +98,7 @@ func (i If) True(r *dns.Msg) bool {
// NewIf creates a new If condition. // NewIf creates a new If condition.
func NewIf(a, operator, b string) (If, error) { func NewIf(a, operator, b string) (If, error) {
if _, ok := conditions[operator]; !ok { if _, ok := conditions[operator]; !ok {
return If{}, operatorError(operator) return If{}, fmt.Errorf("invalid operator %v", operator)
} }
return If{ return If{
A: a, A: a,

View File

@@ -2,7 +2,6 @@
package rewrite package rewrite
import ( import (
"encoding/binary"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"net" "net"
@@ -14,7 +13,7 @@ import (
"github.com/miekg/dns" "github.com/miekg/dns"
) )
// edns0LocalRule is a rewrite rule for EDNS0_LOCAL options // edns0LocalRule is a rewrite rule for EDNS0_LOCAL options.
type edns0LocalRule struct { type edns0LocalRule struct {
mode string mode string
action string action string
@@ -22,7 +21,7 @@ type edns0LocalRule struct {
data []byte data []byte
} }
// edns0VariableRule is a rewrite rule for EDNS0_LOCAL options with variable // edns0VariableRule is a rewrite rule for EDNS0_LOCAL options with variable.
type edns0VariableRule struct { type edns0VariableRule struct {
mode string mode string
action string action string
@@ -30,13 +29,13 @@ type edns0VariableRule struct {
variable string variable string
} }
// ends0NsidRule is a rewrite rule for EDNS0_NSID options // ends0NsidRule is a rewrite rule for EDNS0_NSID options.
type edns0NsidRule struct { type edns0NsidRule struct {
mode string mode string
action string action string
} }
// setupEdns0Opt will retrieve the EDNS0 OPT or create it if it does not exist // setupEdns0Opt will retrieve the EDNS0 OPT or create it if it does not exist.
func setupEdns0Opt(r *dns.Msg) *dns.OPT { func setupEdns0Opt(r *dns.Msg) *dns.OPT {
o := r.IsEdns0() o := r.IsEdns0()
if o == nil { if o == nil {
@@ -47,82 +46,62 @@ func setupEdns0Opt(r *dns.Msg) *dns.OPT {
} }
// Rewrite will alter the request EDNS0 NSID option // Rewrite will alter the request EDNS0 NSID option
func (rule *edns0NsidRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { func (rule *edns0NsidRule) Rewrite(state request.Request) Result {
result := RewriteIgnored o := setupEdns0Opt(state.Req)
o := setupEdns0Opt(r)
found := false
Option:
for _, s := range o.Option { for _, s := range o.Option {
switch e := s.(type) { if e, ok := s.(*dns.EDNS0_NSID); ok {
case *dns.EDNS0_NSID:
if rule.action == Replace || rule.action == Set { if rule.action == Replace || rule.action == Set {
e.Nsid = "" // make sure it is empty for request e.Nsid = "" // make sure it is empty for request
result = RewriteDone return RewriteDone
} }
found = true
break Option
} }
} }
// add option if not found // add option if not found
if !found && (rule.action == Append || rule.action == Set) { if rule.action == Append || rule.action == Set {
o.Option = append(o.Option, &dns.EDNS0_NSID{Code: dns.EDNS0NSID, Nsid: ""}) o.Option = append(o.Option, &dns.EDNS0_NSID{Code: dns.EDNS0NSID, Nsid: ""})
result = RewriteDone return RewriteDone
} }
return result return RewriteIgnored
} }
// Mode returns the processing mode // Mode returns the processing mode.
func (rule *edns0NsidRule) Mode() string { func (rule *edns0NsidRule) Mode() string { return rule.mode }
return rule.mode
}
// GetResponseRule return a rule to rewrite the response with. Currently not implemented. // GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *edns0NsidRule) GetResponseRule() ResponseRule { func (rule *edns0NsidRule) GetResponseRule() ResponseRule { return ResponseRule{} }
return ResponseRule{}
} // Rewrite will alter the request EDNS0 local options.
func (rule *edns0LocalRule) Rewrite(state request.Request) Result {
o := setupEdns0Opt(state.Req)
// Rewrite will alter the request EDNS0 local options
func (rule *edns0LocalRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
result := RewriteIgnored
o := setupEdns0Opt(r)
found := false
for _, s := range o.Option { for _, s := range o.Option {
switch e := s.(type) { if e, ok := s.(*dns.EDNS0_LOCAL); ok {
case *dns.EDNS0_LOCAL:
if rule.code == e.Code { if rule.code == e.Code {
if rule.action == Replace || rule.action == Set { if rule.action == Replace || rule.action == Set {
e.Data = rule.data e.Data = rule.data
result = RewriteDone return RewriteDone
} }
found = true
break
} }
} }
} }
// add option if not found // add option if not found
if !found && (rule.action == Append || rule.action == Set) { if rule.action == Append || rule.action == Set {
var opt dns.EDNS0_LOCAL o.Option = append(o.Option, &dns.EDNS0_LOCAL{Code: rule.code, Data: rule.data})
opt.Code = rule.code return RewriteDone
opt.Data = rule.data
o.Option = append(o.Option, &opt)
result = RewriteDone
} }
return result return RewriteIgnored
} }
// Mode returns the processing mode // Mode returns the processing mode.
func (rule *edns0LocalRule) Mode() string { func (rule *edns0LocalRule) Mode() string { return rule.mode }
return rule.mode
}
// GetResponseRule return a rule to rewrite the response with. Currently not implemented. // GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *edns0LocalRule) GetResponseRule() ResponseRule { func (rule *edns0LocalRule) GetResponseRule() ResponseRule { return ResponseRule{} }
return ResponseRule{}
}
// newEdns0Rule creates an EDNS0 rule of the appropriate type based on the args // newEdns0Rule creates an EDNS0 rule of the appropriate type based on the args
func newEdns0Rule(mode string, args ...string) (Rule, error) { func newEdns0Rule(mode string, args ...string) (Rule, error) {
@@ -145,7 +124,7 @@ func newEdns0Rule(mode string, args ...string) (Rule, error) {
if len(args) != 4 { if len(args) != 4 {
return nil, fmt.Errorf("EDNS0 local rules require exactly three args") return nil, fmt.Errorf("EDNS0 local rules require exactly three args")
} }
//Check for variable option // Check for variable option.
if strings.HasPrefix(args[3], "{") && strings.HasSuffix(args[3], "}") { if strings.HasPrefix(args[3], "{") && strings.HasSuffix(args[3], "}") {
return newEdns0VariableRule(mode, action, args[2], args[3]) return newEdns0VariableRule(mode, action, args[2], args[3])
} }
@@ -194,136 +173,69 @@ func newEdns0VariableRule(mode, action, code, variable string) (*edns0VariableRu
return &edns0VariableRule{mode: mode, action: action, code: uint16(c), variable: variable}, nil return &edns0VariableRule{mode: mode, action: action, code: uint16(c), variable: variable}, nil
} }
// ipToWire writes IP address to wire/binary format, 4 or 16 bytes depends on IPV4 or IPV6. // ruleData returns the data specified by the variable.
func (rule *edns0VariableRule) ipToWire(family int, ipAddr string) ([]byte, error) { func (rule *edns0VariableRule) ruleData(state request.Request) ([]byte, error) {
switch family {
case 1:
return net.ParseIP(ipAddr).To4(), nil
case 2:
return net.ParseIP(ipAddr).To16(), nil
}
return nil, fmt.Errorf("invalid IP address family (i.e. version) %d", family)
}
// uint16ToWire writes unit16 to wire/binary format
func (rule *edns0VariableRule) uint16ToWire(data uint16) []byte {
buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf, uint16(data))
return buf
}
// portToWire writes port to wire/binary format, 2 bytes
func (rule *edns0VariableRule) portToWire(portStr string) ([]byte, error) {
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, err
}
return rule.uint16ToWire(uint16(port)), nil
}
// Family returns the family of the transport, 1 for IPv4 and 2 for IPv6.
func (rule *edns0VariableRule) family(ip net.Addr) int {
var a net.IP
if i, ok := ip.(*net.UDPAddr); ok {
a = i.IP
}
if i, ok := ip.(*net.TCPAddr); ok {
a = i.IP
}
if a.To4() != nil {
return 1
}
return 2
}
// ruleData returns the data specified by the variable
func (rule *edns0VariableRule) ruleData(w dns.ResponseWriter, r *dns.Msg) ([]byte, error) {
req := request.Request{W: w, Req: r}
switch rule.variable { switch rule.variable {
case queryName: case queryName:
//Query name is written as ascii string return []byte(state.QName()), nil
return []byte(req.QName()), nil
case queryType: case queryType:
return rule.uint16ToWire(req.QType()), nil return uint16ToWire(state.QType()), nil
case clientIP: case clientIP:
return rule.ipToWire(req.Family(), req.IP()) return ipToWire(state.Family(), state.IP())
case clientPort:
return rule.portToWire(req.Port())
case protocol:
// Proto is written as ascii string
return []byte(req.Proto()), nil
case serverIP: case serverIP:
ip, _, err := net.SplitHostPort(w.LocalAddr().String()) return ipToWire(state.Family(), state.LocalIP())
if err != nil {
ip = w.RemoteAddr().String() case clientPort:
} return portToWire(state.Port())
return rule.ipToWire(rule.family(w.RemoteAddr()), ip)
case serverPort: case serverPort:
_, port, err := net.SplitHostPort(w.LocalAddr().String()) return portToWire(state.LocalPort())
if err != nil {
port = "0" case protocol:
} return []byte(state.Proto()), nil
return rule.portToWire(port)
} }
return nil, fmt.Errorf("unable to extract data for variable %s", rule.variable) return nil, fmt.Errorf("unable to extract data for variable %s", rule.variable)
} }
// Rewrite will alter the request EDNS0 local options with specified variables // Rewrite will alter the request EDNS0 local options with specified variables.
func (rule *edns0VariableRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { func (rule *edns0VariableRule) Rewrite(state request.Request) Result {
result := RewriteIgnored data, err := rule.ruleData(state)
data, err := rule.ruleData(w, r)
if err != nil || data == nil { if err != nil || data == nil {
return result return RewriteIgnored
} }
o := setupEdns0Opt(r) o := setupEdns0Opt(state.Req)
found := false
for _, s := range o.Option { for _, s := range o.Option {
switch e := s.(type) { if e, ok := s.(*dns.EDNS0_LOCAL); ok {
case *dns.EDNS0_LOCAL:
if rule.code == e.Code { if rule.code == e.Code {
if rule.action == Replace || rule.action == Set { if rule.action == Replace || rule.action == Set {
e.Data = data e.Data = data
result = RewriteDone return RewriteDone
} }
found = true return RewriteIgnored
break
} }
} }
} }
// add option if not found // add option if not found
if !found && (rule.action == Append || rule.action == Set) { if rule.action == Append || rule.action == Set {
var opt dns.EDNS0_LOCAL o.Option = append(o.Option, &dns.EDNS0_LOCAL{Code: rule.code, Data: data})
opt.Code = rule.code return RewriteDone
opt.Data = data
o.Option = append(o.Option, &opt)
result = RewriteDone
} }
return result return RewriteIgnored
} }
// Mode returns the processing mode // Mode returns the processing mode.
func (rule *edns0VariableRule) Mode() string { func (rule *edns0VariableRule) Mode() string { return rule.mode }
return rule.mode
}
// GetResponseRule return a rule to rewrite the response with. Currently not implemented. // GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *edns0VariableRule) GetResponseRule() ResponseRule { func (rule *edns0VariableRule) GetResponseRule() ResponseRule { return ResponseRule{} }
return ResponseRule{}
}
func isValidVariable(variable string) bool { func isValidVariable(variable string) bool {
switch variable { switch variable {
@@ -353,8 +265,8 @@ func newEdns0SubnetRule(mode, action, v4BitMaskLen, v6BitMaskLen string) (*edns0
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Validate V4 length // validate V4 length
if v4Len > maxV4BitMaskLen { if v4Len > net.IPv4len*8 {
return nil, fmt.Errorf("invalid IPv4 bit mask length %d", v4Len) return nil, fmt.Errorf("invalid IPv4 bit mask length %d", v4Len)
} }
@@ -362,8 +274,8 @@ func newEdns0SubnetRule(mode, action, v4BitMaskLen, v6BitMaskLen string) (*edns0
if err != nil { if err != nil {
return nil, err return nil, err
} }
//Validate V6 length // validate V6 length
if v6Len > maxV6BitMaskLen { if v6Len > net.IPv6len*8 {
return nil, fmt.Errorf("invalid IPv6 bit mask length %d", v6Len) return nil, fmt.Errorf("invalid IPv6 bit mask length %d", v6Len)
} }
@@ -372,10 +284,8 @@ func newEdns0SubnetRule(mode, action, v4BitMaskLen, v6BitMaskLen string) (*edns0
} }
// fillEcsData sets the subnet data into the ecs option // fillEcsData sets the subnet data into the ecs option
func (rule *edns0SubnetRule) fillEcsData(w dns.ResponseWriter, r *dns.Msg, ecs *dns.EDNS0_SUBNET) error { func (rule *edns0SubnetRule) fillEcsData(state request.Request, ecs *dns.EDNS0_SUBNET) error {
family := state.Family()
req := request.Request{W: w, Req: r}
family := req.Family()
if (family != 1) && (family != 2) { if (family != 1) && (family != 2) {
return fmt.Errorf("unable to fill data for EDNS0 subnet due to invalid IP family") return fmt.Errorf("unable to fill data for EDNS0 subnet due to invalid IP family")
} }
@@ -383,7 +293,7 @@ func (rule *edns0SubnetRule) fillEcsData(w dns.ResponseWriter, r *dns.Msg, ecs *
ecs.Family = uint16(family) ecs.Family = uint16(family)
ecs.SourceScope = 0 ecs.SourceScope = 0
ipAddr := req.IP() ipAddr := state.IP()
switch family { switch family {
case 1: case 1:
ipv4Mask := net.CIDRMask(int(rule.v4BitMaskLen), 32) ipv4Mask := net.CIDRMask(int(rule.v4BitMaskLen), 32)
@@ -399,45 +309,38 @@ func (rule *edns0SubnetRule) fillEcsData(w dns.ResponseWriter, r *dns.Msg, ecs *
return nil return nil
} }
// Rewrite will alter the request EDNS0 subnet option // Rewrite will alter the request EDNS0 subnet option.
func (rule *edns0SubnetRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { func (rule *edns0SubnetRule) Rewrite(state request.Request) Result {
result := RewriteIgnored o := setupEdns0Opt(state.Req)
o := setupEdns0Opt(r)
found := false
for _, s := range o.Option { for _, s := range o.Option {
switch e := s.(type) { if e, ok := s.(*dns.EDNS0_SUBNET); ok {
case *dns.EDNS0_SUBNET:
if rule.action == Replace || rule.action == Set { if rule.action == Replace || rule.action == Set {
if rule.fillEcsData(w, r, e) == nil { if rule.fillEcsData(state, e) == nil {
result = RewriteDone return RewriteDone
} }
} }
found = true return RewriteIgnored
break
} }
} }
// add option if not found // add option if not found
if !found && (rule.action == Append || rule.action == Set) { if rule.action == Append || rule.action == Set {
opt := dns.EDNS0_SUBNET{Code: dns.EDNS0SUBNET} opt := &dns.EDNS0_SUBNET{Code: dns.EDNS0SUBNET}
if rule.fillEcsData(w, r, &opt) == nil { if rule.fillEcsData(state, opt) == nil {
o.Option = append(o.Option, &opt) o.Option = append(o.Option, opt)
result = RewriteDone return RewriteDone
} }
} }
return result return RewriteIgnored
} }
// Mode returns the processing mode // Mode returns the processing mode
func (rule *edns0SubnetRule) Mode() string { func (rule *edns0SubnetRule) Mode() string { return rule.mode }
return rule.mode
}
// GetResponseRule return a rule to rewrite the response with. Currently not implemented. // GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *edns0SubnetRule) GetResponseRule() ResponseRule { func (rule *edns0SubnetRule) GetResponseRule() ResponseRule { return ResponseRule{} }
return ResponseRule{}
}
// These are all defined actions. // These are all defined actions.
const ( const (
@@ -456,9 +359,3 @@ const (
serverIP = "{server_ip}" serverIP = "{server_ip}"
serverPort = "{server_port}" serverPort = "{server_port}"
) )
// Subnet maximum bit mask length
const (
maxV4BitMaskLen = 32
maxV6BitMaskLen = 128
)

View File

@@ -7,8 +7,7 @@ import (
"strings" "strings"
"github.com/coredns/coredns/plugin" "github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
) )
type nameRule struct { type nameRule struct {
@@ -56,47 +55,47 @@ const (
) )
// Rewrite rewrites the current request based upon exact match of the name // Rewrite rewrites the current request based upon exact match of the name
// in the question section of the request // in the question section of the request.
func (rule *nameRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { func (rule *nameRule) Rewrite(state request.Request) Result {
if rule.From == r.Question[0].Name { if rule.From == state.Name() {
r.Question[0].Name = rule.To state.Req.Question[0].Name = rule.To
return RewriteDone return RewriteDone
} }
return RewriteIgnored return RewriteIgnored
} }
// Rewrite rewrites the current request when the name begins with the matching string // Rewrite rewrites the current request when the name begins with the matching string.
func (rule *prefixNameRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { func (rule *prefixNameRule) Rewrite(state request.Request) Result {
if strings.HasPrefix(r.Question[0].Name, rule.Prefix) { if strings.HasPrefix(state.Name(), rule.Prefix) {
r.Question[0].Name = rule.Replacement + strings.TrimLeft(r.Question[0].Name, rule.Prefix) state.Req.Question[0].Name = rule.Replacement + strings.TrimLeft(state.Name(), rule.Prefix)
return RewriteDone return RewriteDone
} }
return RewriteIgnored return RewriteIgnored
} }
// Rewrite rewrites the current request when the name ends with the matching string // Rewrite rewrites the current request when the name ends with the matching string.
func (rule *suffixNameRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { func (rule *suffixNameRule) Rewrite(state request.Request) Result {
if strings.HasSuffix(r.Question[0].Name, rule.Suffix) { if strings.HasSuffix(state.Name(), rule.Suffix) {
r.Question[0].Name = strings.TrimRight(r.Question[0].Name, rule.Suffix) + rule.Replacement state.Req.Question[0].Name = strings.TrimRight(state.Name(), rule.Suffix) + rule.Replacement
return RewriteDone return RewriteDone
} }
return RewriteIgnored return RewriteIgnored
} }
// Rewrite rewrites the current request based upon partial match of the // Rewrite rewrites the current request based upon partial match of the
// name in the question section of the request // name in the question section of the request.
func (rule *substringNameRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { func (rule *substringNameRule) Rewrite(state request.Request) Result {
if strings.Contains(r.Question[0].Name, rule.Substring) { if strings.Contains(state.Name(), rule.Substring) {
r.Question[0].Name = strings.Replace(r.Question[0].Name, rule.Substring, rule.Replacement, -1) state.Req.Question[0].Name = strings.Replace(state.Name(), rule.Substring, rule.Replacement, -1)
return RewriteDone return RewriteDone
} }
return RewriteIgnored return RewriteIgnored
} }
// Rewrite rewrites the current request when the name in the question // Rewrite rewrites the current request when the name in the question
// section of the request matches a regular expression // section of the request matches a regular expression.
func (rule *regexNameRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { func (rule *regexNameRule) Rewrite(state request.Request) Result {
regexGroups := rule.Pattern.FindStringSubmatch(r.Question[0].Name) regexGroups := rule.Pattern.FindStringSubmatch(state.Name())
if len(regexGroups) == 0 { if len(regexGroups) == 0 {
return RewriteIgnored return RewriteIgnored
} }
@@ -107,7 +106,7 @@ func (rule *regexNameRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
s = strings.Replace(s, groupIndexStr, groupValue, -1) s = strings.Replace(s, groupIndexStr, groupValue, -1)
} }
} }
r.Question[0].Name = s state.Req.Question[0].Name = s
return RewriteDone return RewriteDone
} }
@@ -174,47 +173,23 @@ func newNameRule(nextAction string, args ...string) (Rule, error) {
} }
// Mode returns the processing nextAction // Mode returns the processing nextAction
func (rule *nameRule) Mode() string { func (rule *nameRule) Mode() string { return rule.NextAction }
return rule.NextAction func (rule *prefixNameRule) Mode() string { return rule.NextAction }
} func (rule *suffixNameRule) Mode() string { return rule.NextAction }
func (rule *substringNameRule) Mode() string { return rule.NextAction }
func (rule *prefixNameRule) Mode() string { func (rule *regexNameRule) Mode() string { return rule.NextAction }
return rule.NextAction
}
func (rule *suffixNameRule) Mode() string {
return rule.NextAction
}
func (rule *substringNameRule) Mode() string {
return rule.NextAction
}
func (rule *regexNameRule) Mode() string {
return rule.NextAction
}
// GetResponseRule return a rule to rewrite the response with. Currently not implemented. // GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *nameRule) GetResponseRule() ResponseRule { func (rule *nameRule) GetResponseRule() ResponseRule { return ResponseRule{} }
return ResponseRule{}
}
// GetResponseRule return a rule to rewrite the response with. Currently not implemented. // GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *prefixNameRule) GetResponseRule() ResponseRule { func (rule *prefixNameRule) GetResponseRule() ResponseRule { return ResponseRule{} }
return ResponseRule{}
}
// GetResponseRule return a rule to rewrite the response with. Currently not implemented. // GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *suffixNameRule) GetResponseRule() ResponseRule { func (rule *suffixNameRule) GetResponseRule() ResponseRule { return ResponseRule{} }
return ResponseRule{}
}
// GetResponseRule return a rule to rewrite the response with. Currently not implemented. // GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *substringNameRule) GetResponseRule() ResponseRule { func (rule *substringNameRule) GetResponseRule() ResponseRule { return ResponseRule{} }
return ResponseRule{}
}
// GetResponseRule return a rule to rewrite the response with. // GetResponseRule return a rule to rewrite the response with.
func (rule *regexNameRule) GetResponseRule() ResponseRule { func (rule *regexNameRule) GetResponseRule() ResponseRule { return rule.ResponseRule }
return rule.ResponseRule
}

View File

@@ -33,8 +33,7 @@ func NewResponseReverter(w dns.ResponseWriter, r *dns.Msg) *ResponseReverter {
} }
} }
// WriteMsg records the status code and calls the // WriteMsg records the status code and calls the underlying ResponseWriter's WriteMsg method.
// underlying ResponseWriter's WriteMsg method.
func (r *ResponseReverter) WriteMsg(res *dns.Msg) error { func (r *ResponseReverter) WriteMsg(res *dns.Msg) error {
res.Question[0] = r.originalQuestion res.Question[0] = r.originalQuestion
if r.ResponseRewrite { if r.ResponseRewrite {

View File

@@ -6,6 +6,7 @@ import (
"strings" "strings"
"github.com/coredns/coredns/plugin" "github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/request"
"github.com/miekg/dns" "github.com/miekg/dns"
) )
@@ -38,8 +39,10 @@ type Rewrite struct {
// ServeDNS implements the plugin.Handler interface. // ServeDNS implements the plugin.Handler interface.
func (rw Rewrite) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) { func (rw Rewrite) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
wr := NewResponseReverter(w, r) wr := NewResponseReverter(w, r)
state := request.Request{W: w, Req: r}
for _, rule := range rw.Rules { for _, rule := range rw.Rules {
switch result := rule.Rewrite(w, r); result { switch result := rule.Rewrite(state); result {
case RewriteDone: case RewriteDone:
respRule := rule.GetResponseRule() respRule := rule.GetResponseRule()
if respRule.Active == true { if respRule.Active == true {
@@ -68,7 +71,7 @@ func (rw Rewrite) Name() string { return "rewrite" }
// Rule describes a rewrite rule. // Rule describes a rewrite rule.
type Rule interface { type Rule interface {
// Rewrite rewrites the current request. // Rewrite rewrites the current request.
Rewrite(dns.ResponseWriter, *dns.Msg) Result Rewrite(state request.Request) Result
// Mode returns the processing mode stop or continue. // Mode returns the processing mode stop or continue.
Mode() string Mode() string
// GetResponseRule returns the rule to rewrite response with, if any. // GetResponseRule returns the rule to rewrite response with, if any.

View File

@@ -482,14 +482,14 @@ func TestRewriteEDNS0LocalVariable(t *testing.T) {
}, },
{ {
[]dns.EDNS0{}, []dns.EDNS0{},
[]string{"local", "set", "0xffee", "{server_ip}"}, []string{"local", "set", "0xffee", "{server_port}"},
[]dns.EDNS0{&dns.EDNS0_LOCAL{Code: 0xffee, Data: []byte{0x7F, 0x00, 0x00, 0x01}}}, []dns.EDNS0{&dns.EDNS0_LOCAL{Code: 0xffee, Data: []byte{0x00, 0x35}}},
true, true,
}, },
{ {
[]dns.EDNS0{}, []dns.EDNS0{},
[]string{"local", "set", "0xffee", "{server_port}"}, []string{"local", "set", "0xffee", "{server_ip}"},
[]dns.EDNS0{&dns.EDNS0_LOCAL{Code: 0xffee, Data: []byte{0x00, 0x35}}}, []dns.EDNS0{&dns.EDNS0_LOCAL{Code: 0xffee, Data: []byte{0x7F, 0x00, 0x00, 0x01}}},
true, true,
}, },
} }
@@ -498,7 +498,6 @@ func TestRewriteEDNS0LocalVariable(t *testing.T) {
for i, tc := range tests { for i, tc := range tests {
m := new(dns.Msg) m := new(dns.Msg)
m.SetQuestion("example.com.", dns.TypeA) m.SetQuestion("example.com.", dns.TypeA)
m.Question[0].Qclass = dns.ClassINET
r, err := newEdns0Rule("stop", tc.args...) r, err := newEdns0Rule("stop", tc.args...)
if err != nil { if err != nil {
@@ -620,7 +619,6 @@ func TestRewriteEDNS0Subnet(t *testing.T) {
for i, tc := range tests { for i, tc := range tests {
m := new(dns.Msg) m := new(dns.Msg)
m.SetQuestion("example.com.", dns.TypeA) m.SetQuestion("example.com.", dns.TypeA)
m.Question[0].Qclass = dns.ClassINET
r, err := newEdns0Rule("stop", tc.args...) r, err := newEdns0Rule("stop", tc.args...)
if err != nil { if err != nil {

View File

@@ -1 +0,0 @@
empty

View File

@@ -1,10 +1,12 @@
// Package rewrite is plugin for rewriting requests internally to something different. // Package rewrite is a plugin for rewriting requests internally to something different.
package rewrite package rewrite
import ( import (
"fmt" "fmt"
"strings" "strings"
"github.com/coredns/coredns/request"
"github.com/miekg/dns" "github.com/miekg/dns"
) )
@@ -28,22 +30,18 @@ func newTypeRule(nextAction string, args ...string) (Rule, error) {
} }
// Rewrite rewrites the the current request. // Rewrite rewrites the the current request.
func (rule *typeRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { func (rule *typeRule) Rewrite(state request.Request) Result {
if rule.fromType > 0 && rule.toType > 0 { if rule.fromType > 0 && rule.toType > 0 {
if r.Question[0].Qtype == rule.fromType { if state.QType() == rule.fromType {
r.Question[0].Qtype = rule.toType state.Req.Question[0].Qtype = rule.toType
return RewriteDone return RewriteDone
} }
} }
return RewriteIgnored return RewriteIgnored
} }
// Mode returns the processing mode // Mode returns the processing mode.
func (rule *typeRule) Mode() string { func (rule *typeRule) Mode() string { return rule.nextAction }
return rule.nextAction
}
// GetResponseRule return a rule to rewrite the response with. Currently not implemented. // GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *typeRule) GetResponseRule() ResponseRule { func (rule *typeRule) GetResponseRule() ResponseRule { return ResponseRule{} }
return ResponseRule{}
}

37
plugin/rewrite/wire.go Normal file
View File

@@ -0,0 +1,37 @@
package rewrite
import (
"encoding/binary"
"fmt"
"net"
"strconv"
)
// ipToWire writes IP address to wire/binary format, 4 or 16 bytes depends on IPV4 or IPV6.
func ipToWire(family int, ipAddr string) ([]byte, error) {
switch family {
case 1:
return net.ParseIP(ipAddr).To4(), nil
case 2:
return net.ParseIP(ipAddr).To16(), nil
}
return nil, fmt.Errorf("invalid IP address family (i.e. version) %d", family)
}
// uint16ToWire writes unit16 to wire/binary format
func uint16ToWire(data uint16) []byte {
buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf, uint16(data))
return buf
}
// portToWire writes port to wire/binary format, 2 bytes
func portToWire(portStr string) ([]byte, error) {
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, err
}
return uint16ToWire(uint16(port)), nil
}

View File

@@ -59,6 +59,15 @@ func (r *Request) IP() string {
return r.ip return r.ip
} }
// LocalIP gets the (local) IP address of server handling the request.
func (r *Request) LocalIP() string {
ip, _, err := net.SplitHostPort(r.W.LocalAddr().String())
if err != nil {
return r.W.LocalAddr().String()
}
return ip
}
// Port 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 {
if r.port != "" { if r.port != "" {