Source file src/net/lookup_windows_test.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  	"bytes"
     9  	"context"
    10  	"encoding/json"
    11  	"errors"
    12  	"fmt"
    13  	"internal/testenv"
    14  	"os/exec"
    15  	"reflect"
    16  	"regexp"
    17  	"sort"
    18  	"strings"
    19  	"testing"
    20  )
    21  
    22  var nslookupTestServers = []string{"mail.golang.com", "gmail.com"}
    23  var lookupTestIPs = []string{"8.8.8.8", "1.1.1.1"}
    24  
    25  func toJson(v any) string {
    26  	data, _ := json.Marshal(v)
    27  	return string(data)
    28  }
    29  
    30  func testLookup(t *testing.T, fn func(*testing.T, *Resolver, string)) {
    31  	for _, def := range []bool{true, false} {
    32  		def := def
    33  		for _, server := range nslookupTestServers {
    34  			server := server
    35  			var name string
    36  			if def {
    37  				name = "default/"
    38  			} else {
    39  				name = "go/"
    40  			}
    41  			t.Run(name+server, func(t *testing.T) {
    42  				t.Parallel()
    43  				r := DefaultResolver
    44  				if !def {
    45  					r = &Resolver{PreferGo: true}
    46  				}
    47  				fn(t, r, server)
    48  			})
    49  		}
    50  	}
    51  }
    52  
    53  func TestNSLookupMX(t *testing.T) {
    54  	testenv.MustHaveExternalNetwork(t)
    55  
    56  	testLookup(t, func(t *testing.T, r *Resolver, server string) {
    57  		mx, err := r.LookupMX(context.Background(), server)
    58  		if err != nil {
    59  			t.Fatal(err)
    60  		}
    61  		if len(mx) == 0 {
    62  			t.Fatal("no results")
    63  		}
    64  		expected, err := nslookupMX(server)
    65  		if err != nil {
    66  			t.Skipf("skipping failed nslookup %s test: %s", server, err)
    67  		}
    68  		sort.Sort(byPrefAndHost(expected))
    69  		sort.Sort(byPrefAndHost(mx))
    70  		if !reflect.DeepEqual(expected, mx) {
    71  			t.Errorf("different results %s:\texp:%v\tgot:%v", server, toJson(expected), toJson(mx))
    72  		}
    73  	})
    74  }
    75  
    76  func TestNSLookupCNAME(t *testing.T) {
    77  	testenv.MustHaveExternalNetwork(t)
    78  
    79  	testLookup(t, func(t *testing.T, r *Resolver, server string) {
    80  		cname, err := r.LookupCNAME(context.Background(), server)
    81  		if err != nil {
    82  			t.Fatalf("failed %s: %s", server, err)
    83  		}
    84  		if cname == "" {
    85  			t.Fatalf("no result %s", server)
    86  		}
    87  		expected, err := nslookupCNAME(server)
    88  		if err != nil {
    89  			t.Skipf("skipping failed nslookup %s test: %s", server, err)
    90  		}
    91  		if expected != cname {
    92  			t.Errorf("different results %s:\texp:%v\tgot:%v", server, expected, cname)
    93  		}
    94  	})
    95  }
    96  
    97  func TestNSLookupNS(t *testing.T) {
    98  	testenv.MustHaveExternalNetwork(t)
    99  
   100  	testLookup(t, func(t *testing.T, r *Resolver, server string) {
   101  		ns, err := r.LookupNS(context.Background(), server)
   102  		if err != nil {
   103  			t.Fatalf("failed %s: %s", server, err)
   104  		}
   105  		if len(ns) == 0 {
   106  			t.Fatal("no results")
   107  		}
   108  		expected, err := nslookupNS(server)
   109  		if err != nil {
   110  			t.Skipf("skipping failed nslookup %s test: %s", server, err)
   111  		}
   112  		sort.Sort(byHost(expected))
   113  		sort.Sort(byHost(ns))
   114  		if !reflect.DeepEqual(expected, ns) {
   115  			t.Errorf("different results %s:\texp:%v\tgot:%v", toJson(server), toJson(expected), ns)
   116  		}
   117  	})
   118  }
   119  
   120  func TestNSLookupTXT(t *testing.T) {
   121  	testenv.MustHaveExternalNetwork(t)
   122  
   123  	testLookup(t, func(t *testing.T, r *Resolver, server string) {
   124  		txt, err := r.LookupTXT(context.Background(), server)
   125  		if err != nil {
   126  			t.Fatalf("failed %s: %s", server, err)
   127  		}
   128  		if len(txt) == 0 {
   129  			t.Fatalf("no results")
   130  		}
   131  		expected, err := nslookupTXT(server)
   132  		if err != nil {
   133  			t.Skipf("skipping failed nslookup %s test: %s", server, err)
   134  		}
   135  		sort.Strings(expected)
   136  		sort.Strings(txt)
   137  		if !reflect.DeepEqual(expected, txt) {
   138  			t.Errorf("different results %s:\texp:%v\tgot:%v", server, toJson(expected), toJson(txt))
   139  		}
   140  	})
   141  }
   142  
   143  func TestLookupLocalPTR(t *testing.T) {
   144  	testenv.MustHaveExternalNetwork(t)
   145  
   146  	addr, err := localIP()
   147  	if err != nil {
   148  		t.Errorf("failed to get local ip: %s", err)
   149  	}
   150  	names, err := LookupAddr(addr.String())
   151  	if err != nil {
   152  		t.Errorf("failed %s: %s", addr, err)
   153  	}
   154  	if len(names) == 0 {
   155  		t.Errorf("no results")
   156  	}
   157  	expected, err := lookupPTR(addr.String())
   158  	if err != nil {
   159  		t.Skipf("skipping failed lookup %s test: %s", addr.String(), err)
   160  	}
   161  	sort.Strings(expected)
   162  	sort.Strings(names)
   163  	if !reflect.DeepEqual(expected, names) {
   164  		t.Errorf("different results %s:\texp:%v\tgot:%v", addr, toJson(expected), toJson(names))
   165  	}
   166  }
   167  
   168  func TestLookupPTR(t *testing.T) {
   169  	testenv.MustHaveExternalNetwork(t)
   170  
   171  	for _, addr := range lookupTestIPs {
   172  		names, err := LookupAddr(addr)
   173  		if err != nil {
   174  			t.Errorf("failed %s: %s", addr, err)
   175  		}
   176  		if len(names) == 0 {
   177  			t.Errorf("no results")
   178  		}
   179  		expected, err := lookupPTR(addr)
   180  		if err != nil {
   181  			t.Logf("skipping failed lookup %s test: %s", addr, err)
   182  			continue
   183  		}
   184  		sort.Strings(expected)
   185  		sort.Strings(names)
   186  		if !reflect.DeepEqual(expected, names) {
   187  			t.Errorf("different results %s:\texp:%v\tgot:%v", addr, toJson(expected), toJson(names))
   188  		}
   189  	}
   190  }
   191  
   192  type byPrefAndHost []*MX
   193  
   194  func (s byPrefAndHost) Len() int { return len(s) }
   195  func (s byPrefAndHost) Less(i, j int) bool {
   196  	if s[i].Pref != s[j].Pref {
   197  		return s[i].Pref < s[j].Pref
   198  	}
   199  	return s[i].Host < s[j].Host
   200  }
   201  func (s byPrefAndHost) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
   202  
   203  type byHost []*NS
   204  
   205  func (s byHost) Len() int           { return len(s) }
   206  func (s byHost) Less(i, j int) bool { return s[i].Host < s[j].Host }
   207  func (s byHost) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
   208  
   209  func nslookup(qtype, name string) (string, error) {
   210  	var out bytes.Buffer
   211  	var err bytes.Buffer
   212  	cmd := exec.Command("nslookup", "-querytype="+qtype, name)
   213  	cmd.Stdout = &out
   214  	cmd.Stderr = &err
   215  	if err := cmd.Run(); err != nil {
   216  		return "", err
   217  	}
   218  	r := strings.ReplaceAll(out.String(), "\r\n", "\n")
   219  	// nslookup stderr output contains also debug information such as
   220  	// "Non-authoritative answer" and it doesn't return the correct errcode
   221  	if strings.Contains(err.String(), "can't find") {
   222  		return r, errors.New(err.String())
   223  	}
   224  	return r, nil
   225  }
   226  
   227  func nslookupMX(name string) (mx []*MX, err error) {
   228  	var r string
   229  	if r, err = nslookup("mx", name); err != nil {
   230  		return
   231  	}
   232  	mx = make([]*MX, 0, 10)
   233  	// linux nslookup syntax
   234  	// golang.org      mail exchanger = 2 alt1.aspmx.l.google.com.
   235  	rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+mail exchanger\s*=\s*([0-9]+)\s*([a-z0-9.\-]+)$`)
   236  	for _, ans := range rx.FindAllStringSubmatch(r, -1) {
   237  		pref, _, _ := dtoi(ans[2])
   238  		mx = append(mx, &MX{absDomainName(ans[3]), uint16(pref)})
   239  	}
   240  	// windows nslookup syntax
   241  	// gmail.com       MX preference = 30, mail exchanger = alt3.gmail-smtp-in.l.google.com
   242  	rx = regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+MX preference\s*=\s*([0-9]+)\s*,\s*mail exchanger\s*=\s*([a-z0-9.\-]+)$`)
   243  	for _, ans := range rx.FindAllStringSubmatch(r, -1) {
   244  		pref, _, _ := dtoi(ans[2])
   245  		mx = append(mx, &MX{absDomainName(ans[3]), uint16(pref)})
   246  	}
   247  	return
   248  }
   249  
   250  func nslookupNS(name string) (ns []*NS, err error) {
   251  	var r string
   252  	if r, err = nslookup("ns", name); err != nil {
   253  		return
   254  	}
   255  	ns = make([]*NS, 0, 10)
   256  	// golang.org      nameserver = ns1.google.com.
   257  	rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+nameserver\s*=\s*([a-z0-9.\-]+)$`)
   258  	for _, ans := range rx.FindAllStringSubmatch(r, -1) {
   259  		ns = append(ns, &NS{absDomainName(ans[2])})
   260  	}
   261  	return
   262  }
   263  
   264  func nslookupCNAME(name string) (cname string, err error) {
   265  	var r string
   266  	if r, err = nslookup("cname", name); err != nil {
   267  		return
   268  	}
   269  	// mail.golang.com canonical name = golang.org.
   270  	rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+canonical name\s*=\s*([a-z0-9.\-]+)$`)
   271  	// assumes the last CNAME is the correct one
   272  	last := name
   273  	for _, ans := range rx.FindAllStringSubmatch(r, -1) {
   274  		last = ans[2]
   275  	}
   276  	return absDomainName(last), nil
   277  }
   278  
   279  func nslookupTXT(name string) (txt []string, err error) {
   280  	var r string
   281  	if r, err = nslookup("txt", name); err != nil {
   282  		return
   283  	}
   284  	txt = make([]string, 0, 10)
   285  	// linux
   286  	// golang.org      text = "v=spf1 redirect=_spf.google.com"
   287  
   288  	// windows
   289  	// golang.org      text =
   290  	//
   291  	//    "v=spf1 redirect=_spf.google.com"
   292  	rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+text\s*=\s*"(.*)"$`)
   293  	for _, ans := range rx.FindAllStringSubmatch(r, -1) {
   294  		txt = append(txt, ans[2])
   295  	}
   296  	return
   297  }
   298  
   299  func ping(name string) (string, error) {
   300  	cmd := exec.Command("ping", "-n", "1", "-a", name)
   301  	stdoutStderr, err := cmd.CombinedOutput()
   302  	if err != nil {
   303  		return "", fmt.Errorf("%v: %v", err, string(stdoutStderr))
   304  	}
   305  	r := strings.ReplaceAll(string(stdoutStderr), "\r\n", "\n")
   306  	return r, nil
   307  }
   308  
   309  func lookupPTR(name string) (ptr []string, err error) {
   310  	var r string
   311  	if r, err = ping(name); err != nil {
   312  		return
   313  	}
   314  	ptr = make([]string, 0, 10)
   315  	rx := regexp.MustCompile(`(?m)^Pinging\s+([a-zA-Z0-9.\-]+)\s+\[.*$`)
   316  	for _, ans := range rx.FindAllStringSubmatch(r, -1) {
   317  		ptr = append(ptr, absDomainName(ans[1]))
   318  	}
   319  	return
   320  }
   321  
   322  func localIP() (ip IP, err error) {
   323  	conn, err := Dial("udp", "golang.org:80")
   324  	if err != nil {
   325  		return nil, err
   326  	}
   327  	defer conn.Close()
   328  
   329  	localAddr := conn.LocalAddr().(*UDPAddr)
   330  
   331  	return localAddr.IP, nil
   332  }
   333  

View as plain text