Source file src/net/lookup_windows.go

Documentation: net

     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  	"context"
     9  	"os"
    10  	"runtime"
    11  	"syscall"
    12  	"unsafe"
    13  )
    14  
    15  const _WSAHOST_NOT_FOUND = syscall.Errno(11001)
    16  
    17  func winError(call string, err error) error {
    18  	switch err {
    19  	case _WSAHOST_NOT_FOUND:
    20  		return errNoSuchHost
    21  	}
    22  	return os.NewSyscallError(call, err)
    23  }
    24  
    25  func getprotobyname(name string) (proto int, err error) {
    26  	p, err := syscall.GetProtoByName(name)
    27  	if err != nil {
    28  		return 0, winError("getprotobyname", err)
    29  	}
    30  	return int(p.Proto), nil
    31  }
    32  
    33  // lookupProtocol looks up IP protocol name and returns correspondent protocol number.
    34  func lookupProtocol(ctx context.Context, name string) (int, error) {
    35  	// GetProtoByName return value is stored in thread local storage.
    36  	// Start new os thread before the call to prevent races.
    37  	type result struct {
    38  		proto int
    39  		err   error
    40  	}
    41  	ch := make(chan result) // unbuffered
    42  	go func() {
    43  		acquireThread()
    44  		defer releaseThread()
    45  		runtime.LockOSThread()
    46  		defer runtime.UnlockOSThread()
    47  		proto, err := getprotobyname(name)
    48  		select {
    49  		case ch <- result{proto: proto, err: err}:
    50  		case <-ctx.Done():
    51  		}
    52  	}()
    53  	select {
    54  	case r := <-ch:
    55  		if r.err != nil {
    56  			if proto, err := lookupProtocolMap(name); err == nil {
    57  				return proto, nil
    58  			}
    59  			r.err = &DNSError{Err: r.err.Error(), Name: name}
    60  		}
    61  		return r.proto, r.err
    62  	case <-ctx.Done():
    63  		return 0, mapErr(ctx.Err())
    64  	}
    65  }
    66  
    67  func (r *Resolver) lookupHost(ctx context.Context, name string) ([]string, error) {
    68  	ips, err := r.lookupIP(ctx, "ip", name)
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  	addrs := make([]string, 0, len(ips))
    73  	for _, ip := range ips {
    74  		addrs = append(addrs, ip.String())
    75  	}
    76  	return addrs, nil
    77  }
    78  
    79  func (r *Resolver) lookupIP(ctx context.Context, network, name string) ([]IPAddr, error) {
    80  	// TODO(bradfitz,brainman): use ctx more. See TODO below.
    81  
    82  	var family int32 = syscall.AF_UNSPEC
    83  	switch ipVersion(network) {
    84  	case '4':
    85  		family = syscall.AF_INET
    86  	case '6':
    87  		family = syscall.AF_INET6
    88  	}
    89  
    90  	getaddr := func() ([]IPAddr, error) {
    91  		acquireThread()
    92  		defer releaseThread()
    93  		hints := syscall.AddrinfoW{
    94  			Family:   family,
    95  			Socktype: syscall.SOCK_STREAM,
    96  			Protocol: syscall.IPPROTO_IP,
    97  		}
    98  		var result *syscall.AddrinfoW
    99  		e := syscall.GetAddrInfoW(syscall.StringToUTF16Ptr(name), nil, &hints, &result)
   100  		if e != nil {
   101  			return nil, &DNSError{Err: winError("getaddrinfow", e).Error(), Name: name}
   102  		}
   103  		defer syscall.FreeAddrInfoW(result)
   104  		addrs := make([]IPAddr, 0, 5)
   105  		for ; result != nil; result = result.Next {
   106  			addr := unsafe.Pointer(result.Addr)
   107  			switch result.Family {
   108  			case syscall.AF_INET:
   109  				a := (*syscall.RawSockaddrInet4)(addr).Addr
   110  				addrs = append(addrs, IPAddr{IP: IPv4(a[0], a[1], a[2], a[3])})
   111  			case syscall.AF_INET6:
   112  				a := (*syscall.RawSockaddrInet6)(addr).Addr
   113  				zone := zoneCache.name(int((*syscall.RawSockaddrInet6)(addr).Scope_id))
   114  				addrs = append(addrs, IPAddr{IP: IP{a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]}, Zone: zone})
   115  			default:
   116  				return nil, &DNSError{Err: syscall.EWINDOWS.Error(), Name: name}
   117  			}
   118  		}
   119  		return addrs, nil
   120  	}
   121  
   122  	type ret struct {
   123  		addrs []IPAddr
   124  		err   error
   125  	}
   126  
   127  	ch := make(chan ret, 1)
   128  	go func() {
   129  		addr, err := getaddr()
   130  		ch <- ret{addrs: addr, err: err}
   131  	}()
   132  
   133  	select {
   134  	case r := <-ch:
   135  		return r.addrs, r.err
   136  	case <-ctx.Done():
   137  		// TODO(bradfitz,brainman): cancel the ongoing
   138  		// GetAddrInfoW? It would require conditionally using
   139  		// GetAddrInfoEx with lpOverlapped, which requires
   140  		// Windows 8 or newer. I guess we'll need oldLookupIP,
   141  		// newLookupIP, and newerLookUP.
   142  		//
   143  		// For now we just let it finish and write to the
   144  		// buffered channel.
   145  		return nil, &DNSError{
   146  			Name:      name,
   147  			Err:       ctx.Err().Error(),
   148  			IsTimeout: ctx.Err() == context.DeadlineExceeded,
   149  		}
   150  	}
   151  }
   152  
   153  func (r *Resolver) lookupPort(ctx context.Context, network, service string) (int, error) {
   154  	if r.preferGo() {
   155  		return lookupPortMap(network, service)
   156  	}
   157  
   158  	// TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
   159  	acquireThread()
   160  	defer releaseThread()
   161  	var stype int32
   162  	switch network {
   163  	case "tcp4", "tcp6":
   164  		stype = syscall.SOCK_STREAM
   165  	case "udp4", "udp6":
   166  		stype = syscall.SOCK_DGRAM
   167  	}
   168  	hints := syscall.AddrinfoW{
   169  		Family:   syscall.AF_UNSPEC,
   170  		Socktype: stype,
   171  		Protocol: syscall.IPPROTO_IP,
   172  	}
   173  	var result *syscall.AddrinfoW
   174  	e := syscall.GetAddrInfoW(nil, syscall.StringToUTF16Ptr(service), &hints, &result)
   175  	if e != nil {
   176  		if port, err := lookupPortMap(network, service); err == nil {
   177  			return port, nil
   178  		}
   179  		return 0, &DNSError{Err: winError("getaddrinfow", e).Error(), Name: network + "/" + service}
   180  	}
   181  	defer syscall.FreeAddrInfoW(result)
   182  	if result == nil {
   183  		return 0, &DNSError{Err: syscall.EINVAL.Error(), Name: network + "/" + service}
   184  	}
   185  	addr := unsafe.Pointer(result.Addr)
   186  	switch result.Family {
   187  	case syscall.AF_INET:
   188  		a := (*syscall.RawSockaddrInet4)(addr)
   189  		return int(syscall.Ntohs(a.Port)), nil
   190  	case syscall.AF_INET6:
   191  		a := (*syscall.RawSockaddrInet6)(addr)
   192  		return int(syscall.Ntohs(a.Port)), nil
   193  	}
   194  	return 0, &DNSError{Err: syscall.EINVAL.Error(), Name: network + "/" + service}
   195  }
   196  
   197  func (*Resolver) lookupCNAME(ctx context.Context, name string) (string, error) {
   198  	// TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
   199  	acquireThread()
   200  	defer releaseThread()
   201  	var r *syscall.DNSRecord
   202  	e := syscall.DnsQuery(name, syscall.DNS_TYPE_CNAME, 0, nil, &r, nil)
   203  	// windows returns DNS_INFO_NO_RECORDS if there are no CNAME-s
   204  	if errno, ok := e.(syscall.Errno); ok && errno == syscall.DNS_INFO_NO_RECORDS {
   205  		// if there are no aliases, the canonical name is the input name
   206  		return absDomainName([]byte(name)), nil
   207  	}
   208  	if e != nil {
   209  		return "", &DNSError{Err: winError("dnsquery", e).Error(), Name: name}
   210  	}
   211  	defer syscall.DnsRecordListFree(r, 1)
   212  
   213  	resolved := resolveCNAME(syscall.StringToUTF16Ptr(name), r)
   214  	cname := syscall.UTF16ToString((*[256]uint16)(unsafe.Pointer(resolved))[:])
   215  	return absDomainName([]byte(cname)), nil
   216  }
   217  
   218  func (*Resolver) lookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error) {
   219  	// TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
   220  	acquireThread()
   221  	defer releaseThread()
   222  	var target string
   223  	if service == "" && proto == "" {
   224  		target = name
   225  	} else {
   226  		target = "_" + service + "._" + proto + "." + name
   227  	}
   228  	var r *syscall.DNSRecord
   229  	e := syscall.DnsQuery(target, syscall.DNS_TYPE_SRV, 0, nil, &r, nil)
   230  	if e != nil {
   231  		return "", nil, &DNSError{Err: winError("dnsquery", e).Error(), Name: target}
   232  	}
   233  	defer syscall.DnsRecordListFree(r, 1)
   234  
   235  	srvs := make([]*SRV, 0, 10)
   236  	for _, p := range validRecs(r, syscall.DNS_TYPE_SRV, target) {
   237  		v := (*syscall.DNSSRVData)(unsafe.Pointer(&p.Data[0]))
   238  		srvs = append(srvs, &SRV{absDomainName([]byte(syscall.UTF16ToString((*[256]uint16)(unsafe.Pointer(v.Target))[:]))), v.Port, v.Priority, v.Weight})
   239  	}
   240  	byPriorityWeight(srvs).sort()
   241  	return absDomainName([]byte(target)), srvs, nil
   242  }
   243  
   244  func (*Resolver) lookupMX(ctx context.Context, name string) ([]*MX, error) {
   245  	// TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
   246  	acquireThread()
   247  	defer releaseThread()
   248  	var r *syscall.DNSRecord
   249  	e := syscall.DnsQuery(name, syscall.DNS_TYPE_MX, 0, nil, &r, nil)
   250  	if e != nil {
   251  		return nil, &DNSError{Err: winError("dnsquery", e).Error(), Name: name}
   252  	}
   253  	defer syscall.DnsRecordListFree(r, 1)
   254  
   255  	mxs := make([]*MX, 0, 10)
   256  	for _, p := range validRecs(r, syscall.DNS_TYPE_MX, name) {
   257  		v := (*syscall.DNSMXData)(unsafe.Pointer(&p.Data[0]))
   258  		mxs = append(mxs, &MX{absDomainName([]byte(syscall.UTF16ToString((*[256]uint16)(unsafe.Pointer(v.NameExchange))[:]))), v.Preference})
   259  	}
   260  	byPref(mxs).sort()
   261  	return mxs, nil
   262  }
   263  
   264  func (*Resolver) lookupNS(ctx context.Context, name string) ([]*NS, error) {
   265  	// TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
   266  	acquireThread()
   267  	defer releaseThread()
   268  	var r *syscall.DNSRecord
   269  	e := syscall.DnsQuery(name, syscall.DNS_TYPE_NS, 0, nil, &r, nil)
   270  	if e != nil {
   271  		return nil, &DNSError{Err: winError("dnsquery", e).Error(), Name: name}
   272  	}
   273  	defer syscall.DnsRecordListFree(r, 1)
   274  
   275  	nss := make([]*NS, 0, 10)
   276  	for _, p := range validRecs(r, syscall.DNS_TYPE_NS, name) {
   277  		v := (*syscall.DNSPTRData)(unsafe.Pointer(&p.Data[0]))
   278  		nss = append(nss, &NS{absDomainName([]byte(syscall.UTF16ToString((*[256]uint16)(unsafe.Pointer(v.Host))[:])))})
   279  	}
   280  	return nss, nil
   281  }
   282  
   283  func (*Resolver) lookupTXT(ctx context.Context, name string) ([]string, error) {
   284  	// TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
   285  	acquireThread()
   286  	defer releaseThread()
   287  	var r *syscall.DNSRecord
   288  	e := syscall.DnsQuery(name, syscall.DNS_TYPE_TEXT, 0, nil, &r, nil)
   289  	if e != nil {
   290  		return nil, &DNSError{Err: winError("dnsquery", e).Error(), Name: name}
   291  	}
   292  	defer syscall.DnsRecordListFree(r, 1)
   293  
   294  	txts := make([]string, 0, 10)
   295  	for _, p := range validRecs(r, syscall.DNS_TYPE_TEXT, name) {
   296  		d := (*syscall.DNSTXTData)(unsafe.Pointer(&p.Data[0]))
   297  		s := ""
   298  		for _, v := range (*[1 << 10]*uint16)(unsafe.Pointer(&(d.StringArray[0])))[:d.StringCount] {
   299  			s += syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(v))[:])
   300  		}
   301  		txts = append(txts, s)
   302  	}
   303  	return txts, nil
   304  }
   305  
   306  func (*Resolver) lookupAddr(ctx context.Context, addr string) ([]string, error) {
   307  	// TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
   308  	acquireThread()
   309  	defer releaseThread()
   310  	arpa, err := reverseaddr(addr)
   311  	if err != nil {
   312  		return nil, err
   313  	}
   314  	var r *syscall.DNSRecord
   315  	e := syscall.DnsQuery(arpa, syscall.DNS_TYPE_PTR, 0, nil, &r, nil)
   316  	if e != nil {
   317  		return nil, &DNSError{Err: winError("dnsquery", e).Error(), Name: addr}
   318  	}
   319  	defer syscall.DnsRecordListFree(r, 1)
   320  
   321  	ptrs := make([]string, 0, 10)
   322  	for _, p := range validRecs(r, syscall.DNS_TYPE_PTR, arpa) {
   323  		v := (*syscall.DNSPTRData)(unsafe.Pointer(&p.Data[0]))
   324  		ptrs = append(ptrs, absDomainName([]byte(syscall.UTF16ToString((*[256]uint16)(unsafe.Pointer(v.Host))[:]))))
   325  	}
   326  	return ptrs, nil
   327  }
   328  
   329  const dnsSectionMask = 0x0003
   330  
   331  // returns only results applicable to name and resolves CNAME entries
   332  func validRecs(r *syscall.DNSRecord, dnstype uint16, name string) []*syscall.DNSRecord {
   333  	cname := syscall.StringToUTF16Ptr(name)
   334  	if dnstype != syscall.DNS_TYPE_CNAME {
   335  		cname = resolveCNAME(cname, r)
   336  	}
   337  	rec := make([]*syscall.DNSRecord, 0, 10)
   338  	for p := r; p != nil; p = p.Next {
   339  		if p.Dw&dnsSectionMask != syscall.DnsSectionAnswer {
   340  			continue
   341  		}
   342  		if p.Type != dnstype {
   343  			continue
   344  		}
   345  		if !syscall.DnsNameCompare(cname, p.Name) {
   346  			continue
   347  		}
   348  		rec = append(rec, p)
   349  	}
   350  	return rec
   351  }
   352  
   353  // returns the last CNAME in chain
   354  func resolveCNAME(name *uint16, r *syscall.DNSRecord) *uint16 {
   355  	// limit cname resolving to 10 in case of a infinite CNAME loop
   356  Cname:
   357  	for cnameloop := 0; cnameloop < 10; cnameloop++ {
   358  		for p := r; p != nil; p = p.Next {
   359  			if p.Dw&dnsSectionMask != syscall.DnsSectionAnswer {
   360  				continue
   361  			}
   362  			if p.Type != syscall.DNS_TYPE_CNAME {
   363  				continue
   364  			}
   365  			if !syscall.DnsNameCompare(name, p.Name) {
   366  				continue
   367  			}
   368  			name = (*syscall.DNSPTRData)(unsafe.Pointer(&r.Data[0])).Host
   369  			continue Cname
   370  		}
   371  		break
   372  	}
   373  	return name
   374  }
   375  
   376  // concurrentThreadsLimit returns the number of threads we permit to
   377  // run concurrently doing DNS lookups.
   378  func concurrentThreadsLimit() int {
   379  	return 500
   380  }
   381  

View as plain text