github.com/elfadel/cilium@v1.6.12/pkg/fqdn/dnsproxy/helpers.go (about)

     1  // Copyright 2018 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package dnsproxy
    16  
    17  import (
    18  	"fmt"
    19  	"net"
    20  	"strings"
    21  
    22  	"github.com/miekg/dns"
    23  )
    24  
    25  // prepareNameMatch ensures that a name is an anchored regexp and that names
    26  // with only "." (aka not a regexp) escape the "." so it does not match any
    27  // character. DNS expects lowercase lookups (ignoring the highest ascii bit)
    28  // and we mimic this by lowercasing the name here, and lookups later.
    29  // Note: The trailing "." in a FQDN is assumed, and isn't added here.
    30  func prepareNameMatch(name string) string {
    31  	name = strings.ToLower(name) // lowercase it
    32  
    33  	// anchor it
    34  	out := make([]string, 0, 3)
    35  	if !strings.HasPrefix(name, "^") {
    36  		out = append(out, "^")
    37  	}
    38  	out = append(out, name)
    39  	if !strings.HasSuffix(name, "$") {
    40  		out = append(out, "$")
    41  	}
    42  	return strings.Join(out, "")
    43  }
    44  
    45  // lookupTargetDNSServer finds the intended DNS target server for a specific
    46  // request (passed in via ServeDNS). The IP:port combination is
    47  // returned.
    48  func lookupTargetDNSServer(w dns.ResponseWriter) (serverIP net.IP, serverPort uint16, addrStr string, err error) {
    49  	switch addr := (w.LocalAddr()).(type) {
    50  	case *net.UDPAddr:
    51  		return addr.IP, uint16(addr.Port), addr.String(), nil
    52  	case *net.TCPAddr:
    53  		return addr.IP, uint16(addr.Port), addr.String(), nil
    54  	default:
    55  		return nil, 0, addr.String(), fmt.Errorf("Cannot extract address information for type %T: %+v", addr, addr)
    56  	}
    57  }