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"
"strings"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
)
@@ -27,22 +29,18 @@ func newClassRule(nextAction string, args ...string) (Rule, error) {
}
// 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 r.Question[0].Qclass == rule.fromClass {
r.Question[0].Qclass = rule.toClass
if state.Req.Question[0].Qclass == rule.fromClass {
state.Req.Question[0].Qclass = rule.toClass
return RewriteDone
}
}
return RewriteIgnored
}
// Mode returns the processing mode
func (rule *classRule) Mode() string {
return rule.NextAction
}
// Mode returns the processing mode.
func (rule *classRule) Mode() string { return rule.NextAction }
// GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *classRule) GetResponseRule() ResponseRule {
return ResponseRule{}
}
func (rule *classRule) GetResponseRule() ResponseRule { return ResponseRule{} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -482,14 +482,14 @@ func TestRewriteEDNS0LocalVariable(t *testing.T) {
},
{
[]dns.EDNS0{},
[]string{"local", "set", "0xffee", "{server_ip}"},
[]dns.EDNS0{&dns.EDNS0_LOCAL{Code: 0xffee, Data: []byte{0x7F, 0x00, 0x00, 0x01}}},
[]string{"local", "set", "0xffee", "{server_port}"},
[]dns.EDNS0{&dns.EDNS0_LOCAL{Code: 0xffee, Data: []byte{0x00, 0x35}}},
true,
},
{
[]dns.EDNS0{},
[]string{"local", "set", "0xffee", "{server_port}"},
[]dns.EDNS0{&dns.EDNS0_LOCAL{Code: 0xffee, Data: []byte{0x00, 0x35}}},
[]string{"local", "set", "0xffee", "{server_ip}"},
[]dns.EDNS0{&dns.EDNS0_LOCAL{Code: 0xffee, Data: []byte{0x7F, 0x00, 0x00, 0x01}}},
true,
},
}
@@ -498,7 +498,6 @@ func TestRewriteEDNS0LocalVariable(t *testing.T) {
for i, tc := range tests {
m := new(dns.Msg)
m.SetQuestion("example.com.", dns.TypeA)
m.Question[0].Qclass = dns.ClassINET
r, err := newEdns0Rule("stop", tc.args...)
if err != nil {
@@ -620,7 +619,6 @@ func TestRewriteEDNS0Subnet(t *testing.T) {
for i, tc := range tests {
m := new(dns.Msg)
m.SetQuestion("example.com.", dns.TypeA)
m.Question[0].Qclass = dns.ClassINET
r, err := newEdns0Rule("stop", tc.args...)
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
import (
"fmt"
"strings"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
)
@@ -28,22 +30,18 @@ func newTypeRule(nextAction string, args ...string) (Rule, error) {
}
// 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 r.Question[0].Qtype == rule.fromType {
r.Question[0].Qtype = rule.toType
if state.QType() == rule.fromType {
state.Req.Question[0].Qtype = rule.toType
return RewriteDone
}
}
return RewriteIgnored
}
// Mode returns the processing mode
func (rule *typeRule) Mode() string {
return rule.nextAction
}
// Mode returns the processing mode.
func (rule *typeRule) Mode() string { return rule.nextAction }
// GetResponseRule return a rule to rewrite the response with. Currently not implemented.
func (rule *typeRule) GetResponseRule() ResponseRule {
return ResponseRule{}
}
func (rule *typeRule) GetResponseRule() 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
}
// 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.
func (r *Request) Port() string {
if r.port != "" {