...
Run Format

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

View as plain text