Source file src/net/dnsclient.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package net
     6  
     7  import (
     8  	"internal/bytealg"
     9  	"internal/itoa"
    10  	"sort"
    11  	_ "unsafe" // for go:linkname
    12  
    13  	"golang.org/x/net/dns/dnsmessage"
    14  )
    15  
    16  // provided by runtime
    17  //go:linkname runtime_rand runtime.rand
    18  func runtime_rand() uint64
    19  
    20  func randInt() int {
    21  	return int(uint(runtime_rand()) >> 1) // clear sign bit
    22  }
    23  
    24  func randIntn(n int) int {
    25  	return randInt() % n
    26  }
    27  
    28  // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
    29  // address addr suitable for rDNS (PTR) record lookup or an error if it fails
    30  // to parse the IP address.
    31  func reverseaddr(addr string) (arpa string, err error) {
    32  	ip := ParseIP(addr)
    33  	if ip == nil {
    34  		return "", &DNSError{Err: "unrecognized address", Name: addr}
    35  	}
    36  	if ip.To4() != nil {
    37  		return itoa.Uitoa(uint(ip[15])) + "." + itoa.Uitoa(uint(ip[14])) + "." + itoa.Uitoa(uint(ip[13])) + "." + itoa.Uitoa(uint(ip[12])) + ".in-addr.arpa.", nil
    38  	}
    39  	// Must be IPv6
    40  	buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
    41  	// Add it, in reverse, to the buffer
    42  	for i := len(ip) - 1; i >= 0; i-- {
    43  		v := ip[i]
    44  		buf = append(buf, hexDigit[v&0xF],
    45  			'.',
    46  			hexDigit[v>>4],
    47  			'.')
    48  	}
    49  	// Append "ip6.arpa." and return (buf already has the final .)
    50  	buf = append(buf, "ip6.arpa."...)
    51  	return string(buf), nil
    52  }
    53  
    54  func equalASCIIName(x, y dnsmessage.Name) bool {
    55  	if x.Length != y.Length {
    56  		return false
    57  	}
    58  	for i := 0; i < int(x.Length); i++ {
    59  		a := x.Data[i]
    60  		b := y.Data[i]
    61  		if 'A' <= a && a <= 'Z' {
    62  			a += 0x20
    63  		}
    64  		if 'A' <= b && b <= 'Z' {
    65  			b += 0x20
    66  		}
    67  		if a != b {
    68  			return false
    69  		}
    70  	}
    71  	return true
    72  }
    73  
    74  // isDomainName checks if a string is a presentation-format domain name
    75  // (currently restricted to hostname-compatible "preferred name" LDH labels and
    76  // SRV-like "underscore labels"; see golang.org/issue/12421).
    77  func isDomainName(s string) bool {
    78  	// The root domain name is valid. See golang.org/issue/45715.
    79  	if s == "." {
    80  		return true
    81  	}
    82  
    83  	// See RFC 1035, RFC 3696.
    84  	// Presentation format has dots before every label except the first, and the
    85  	// terminal empty label is optional here because we assume fully-qualified
    86  	// (absolute) input. We must therefore reserve space for the first and last
    87  	// labels' length octets in wire format, where they are necessary and the
    88  	// maximum total length is 255.
    89  	// So our _effective_ maximum is 253, but 254 is not rejected if the last
    90  	// character is a dot.
    91  	l := len(s)
    92  	if l == 0 || l > 254 || l == 254 && s[l-1] != '.' {
    93  		return false
    94  	}
    95  
    96  	last := byte('.')
    97  	nonNumeric := false // true once we've seen a letter or hyphen
    98  	partlen := 0
    99  	for i := 0; i < len(s); i++ {
   100  		c := s[i]
   101  		switch {
   102  		default:
   103  			return false
   104  		case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_':
   105  			nonNumeric = true
   106  			partlen++
   107  		case '0' <= c && c <= '9':
   108  			// fine
   109  			partlen++
   110  		case c == '-':
   111  			// Byte before dash cannot be dot.
   112  			if last == '.' {
   113  				return false
   114  			}
   115  			partlen++
   116  			nonNumeric = true
   117  		case c == '.':
   118  			// Byte before dot cannot be dot, dash.
   119  			if last == '.' || last == '-' {
   120  				return false
   121  			}
   122  			if partlen > 63 || partlen == 0 {
   123  				return false
   124  			}
   125  			partlen = 0
   126  		}
   127  		last = c
   128  	}
   129  	if last == '-' || partlen > 63 {
   130  		return false
   131  	}
   132  
   133  	return nonNumeric
   134  }
   135  
   136  // absDomainName returns an absolute domain name which ends with a
   137  // trailing dot to match pure Go reverse resolver and all other lookup
   138  // routines.
   139  // See golang.org/issue/12189.
   140  // But we don't want to add dots for local names from /etc/hosts.
   141  // It's hard to tell so we settle on the heuristic that names without dots
   142  // (like "localhost" or "myhost") do not get trailing dots, but any other
   143  // names do.
   144  func absDomainName(s string) string {
   145  	if bytealg.IndexByteString(s, '.') != -1 && s[len(s)-1] != '.' {
   146  		s += "."
   147  	}
   148  	return s
   149  }
   150  
   151  // An SRV represents a single DNS SRV record.
   152  type SRV struct {
   153  	Target   string
   154  	Port     uint16
   155  	Priority uint16
   156  	Weight   uint16
   157  }
   158  
   159  // byPriorityWeight sorts SRV records by ascending priority and weight.
   160  type byPriorityWeight []*SRV
   161  
   162  func (s byPriorityWeight) Len() int { return len(s) }
   163  func (s byPriorityWeight) Less(i, j int) bool {
   164  	return s[i].Priority < s[j].Priority || (s[i].Priority == s[j].Priority && s[i].Weight < s[j].Weight)
   165  }
   166  func (s byPriorityWeight) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
   167  
   168  // shuffleByWeight shuffles SRV records by weight using the algorithm
   169  // described in RFC 2782.
   170  func (addrs byPriorityWeight) shuffleByWeight() {
   171  	sum := 0
   172  	for _, addr := range addrs {
   173  		sum += int(addr.Weight)
   174  	}
   175  	for sum > 0 && len(addrs) > 1 {
   176  		s := 0
   177  		n := randIntn(sum)
   178  		for i := range addrs {
   179  			s += int(addrs[i].Weight)
   180  			if s > n {
   181  				if i > 0 {
   182  					addrs[0], addrs[i] = addrs[i], addrs[0]
   183  				}
   184  				break
   185  			}
   186  		}
   187  		sum -= int(addrs[0].Weight)
   188  		addrs = addrs[1:]
   189  	}
   190  }
   191  
   192  // sort reorders SRV records as specified in RFC 2782.
   193  func (addrs byPriorityWeight) sort() {
   194  	sort.Sort(addrs)
   195  	i := 0
   196  	for j := 1; j < len(addrs); j++ {
   197  		if addrs[i].Priority != addrs[j].Priority {
   198  			addrs[i:j].shuffleByWeight()
   199  			i = j
   200  		}
   201  	}
   202  	addrs[i:].shuffleByWeight()
   203  }
   204  
   205  // An MX represents a single DNS MX record.
   206  type MX struct {
   207  	Host string
   208  	Pref uint16
   209  }
   210  
   211  // byPref implements sort.Interface to sort MX records by preference
   212  type byPref []*MX
   213  
   214  func (s byPref) Len() int           { return len(s) }
   215  func (s byPref) Less(i, j int) bool { return s[i].Pref < s[j].Pref }
   216  func (s byPref) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
   217  
   218  // sort reorders MX records as specified in RFC 5321.
   219  func (s byPref) sort() {
   220  	for i := range s {
   221  		j := randIntn(i + 1)
   222  		s[i], s[j] = s[j], s[i]
   223  	}
   224  	sort.Sort(s)
   225  }
   226  
   227  // An NS represents a single DNS NS record.
   228  type NS struct {
   229  	Host string
   230  }
   231  

View as plain text