Black Lives Matter. Support the Equal Justice Initiative.

Source file src/net/dial.go

Documentation: net

     1  // Copyright 2010 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  	"internal/nettrace"
    10  	"syscall"
    11  	"time"
    12  )
    13  
    14  // defaultTCPKeepAlive is a default constant value for TCPKeepAlive times
    15  // See golang.org/issue/31510
    16  const (
    17  	defaultTCPKeepAlive = 15 * time.Second
    18  )
    19  
    20  // A Dialer contains options for connecting to an address.
    21  //
    22  // The zero value for each field is equivalent to dialing
    23  // without that option. Dialing with the zero value of Dialer
    24  // is therefore equivalent to just calling the Dial function.
    25  //
    26  // It is safe to call Dialer's methods concurrently.
    27  type Dialer struct {
    28  	// Timeout is the maximum amount of time a dial will wait for
    29  	// a connect to complete. If Deadline is also set, it may fail
    30  	// earlier.
    31  	//
    32  	// The default is no timeout.
    33  	//
    34  	// When using TCP and dialing a host name with multiple IP
    35  	// addresses, the timeout may be divided between them.
    36  	//
    37  	// With or without a timeout, the operating system may impose
    38  	// its own earlier timeout. For instance, TCP timeouts are
    39  	// often around 3 minutes.
    40  	Timeout time.Duration
    41  
    42  	// Deadline is the absolute point in time after which dials
    43  	// will fail. If Timeout is set, it may fail earlier.
    44  	// Zero means no deadline, or dependent on the operating system
    45  	// as with the Timeout option.
    46  	Deadline time.Time
    47  
    48  	// LocalAddr is the local address to use when dialing an
    49  	// address. The address must be of a compatible type for the
    50  	// network being dialed.
    51  	// If nil, a local address is automatically chosen.
    52  	LocalAddr Addr
    53  
    54  	// DualStack previously enabled RFC 6555 Fast Fallback
    55  	// support, also known as "Happy Eyeballs", in which IPv4 is
    56  	// tried soon if IPv6 appears to be misconfigured and
    57  	// hanging.
    58  	//
    59  	// Deprecated: Fast Fallback is enabled by default. To
    60  	// disable, set FallbackDelay to a negative value.
    61  	DualStack bool
    62  
    63  	// FallbackDelay specifies the length of time to wait before
    64  	// spawning a RFC 6555 Fast Fallback connection. That is, this
    65  	// is the amount of time to wait for IPv6 to succeed before
    66  	// assuming that IPv6 is misconfigured and falling back to
    67  	// IPv4.
    68  	//
    69  	// If zero, a default delay of 300ms is used.
    70  	// A negative value disables Fast Fallback support.
    71  	FallbackDelay time.Duration
    72  
    73  	// KeepAlive specifies the interval between keep-alive
    74  	// probes for an active network connection.
    75  	// If zero, keep-alive probes are sent with a default value
    76  	// (currently 15 seconds), if supported by the protocol and operating
    77  	// system. Network protocols or operating systems that do
    78  	// not support keep-alives ignore this field.
    79  	// If negative, keep-alive probes are disabled.
    80  	KeepAlive time.Duration
    81  
    82  	// Resolver optionally specifies an alternate resolver to use.
    83  	Resolver *Resolver
    84  
    85  	// Cancel is an optional channel whose closure indicates that
    86  	// the dial should be canceled. Not all types of dials support
    87  	// cancellation.
    88  	//
    89  	// Deprecated: Use DialContext instead.
    90  	Cancel <-chan struct{}
    91  
    92  	// If Control is not nil, it is called after creating the network
    93  	// connection but before actually dialing.
    94  	//
    95  	// Network and address parameters passed to Control method are not
    96  	// necessarily the ones passed to Dial. For example, passing "tcp" to Dial
    97  	// will cause the Control function to be called with "tcp4" or "tcp6".
    98  	Control func(network, address string, c syscall.RawConn) error
    99  }
   100  
   101  func (d *Dialer) dualStack() bool { return d.FallbackDelay >= 0 }
   102  
   103  func minNonzeroTime(a, b time.Time) time.Time {
   104  	if a.IsZero() {
   105  		return b
   106  	}
   107  	if b.IsZero() || a.Before(b) {
   108  		return a
   109  	}
   110  	return b
   111  }
   112  
   113  // deadline returns the earliest of:
   114  //   - now+Timeout
   115  //   - d.Deadline
   116  //   - the context's deadline
   117  // Or zero, if none of Timeout, Deadline, or context's deadline is set.
   118  func (d *Dialer) deadline(ctx context.Context, now time.Time) (earliest time.Time) {
   119  	if d.Timeout != 0 { // including negative, for historical reasons
   120  		earliest = now.Add(d.Timeout)
   121  	}
   122  	if d, ok := ctx.Deadline(); ok {
   123  		earliest = minNonzeroTime(earliest, d)
   124  	}
   125  	return minNonzeroTime(earliest, d.Deadline)
   126  }
   127  
   128  func (d *Dialer) resolver() *Resolver {
   129  	if d.Resolver != nil {
   130  		return d.Resolver
   131  	}
   132  	return DefaultResolver
   133  }
   134  
   135  // partialDeadline returns the deadline to use for a single address,
   136  // when multiple addresses are pending.
   137  func partialDeadline(now, deadline time.Time, addrsRemaining int) (time.Time, error) {
   138  	if deadline.IsZero() {
   139  		return deadline, nil
   140  	}
   141  	timeRemaining := deadline.Sub(now)
   142  	if timeRemaining <= 0 {
   143  		return time.Time{}, errTimeout
   144  	}
   145  	// Tentatively allocate equal time to each remaining address.
   146  	timeout := timeRemaining / time.Duration(addrsRemaining)
   147  	// If the time per address is too short, steal from the end of the list.
   148  	const saneMinimum = 2 * time.Second
   149  	if timeout < saneMinimum {
   150  		if timeRemaining < saneMinimum {
   151  			timeout = timeRemaining
   152  		} else {
   153  			timeout = saneMinimum
   154  		}
   155  	}
   156  	return now.Add(timeout), nil
   157  }
   158  
   159  func (d *Dialer) fallbackDelay() time.Duration {
   160  	if d.FallbackDelay > 0 {
   161  		return d.FallbackDelay
   162  	} else {
   163  		return 300 * time.Millisecond
   164  	}
   165  }
   166  
   167  func parseNetwork(ctx context.Context, network string, needsProto bool) (afnet string, proto int, err error) {
   168  	i := last(network, ':')
   169  	if i < 0 { // no colon
   170  		switch network {
   171  		case "tcp", "tcp4", "tcp6":
   172  		case "udp", "udp4", "udp6":
   173  		case "ip", "ip4", "ip6":
   174  			if needsProto {
   175  				return "", 0, UnknownNetworkError(network)
   176  			}
   177  		case "unix", "unixgram", "unixpacket":
   178  		default:
   179  			return "", 0, UnknownNetworkError(network)
   180  		}
   181  		return network, 0, nil
   182  	}
   183  	afnet = network[:i]
   184  	switch afnet {
   185  	case "ip", "ip4", "ip6":
   186  		protostr := network[i+1:]
   187  		proto, i, ok := dtoi(protostr)
   188  		if !ok || i != len(protostr) {
   189  			proto, err = lookupProtocol(ctx, protostr)
   190  			if err != nil {
   191  				return "", 0, err
   192  			}
   193  		}
   194  		return afnet, proto, nil
   195  	}
   196  	return "", 0, UnknownNetworkError(network)
   197  }
   198  
   199  // resolveAddrList resolves addr using hint and returns a list of
   200  // addresses. The result contains at least one address when error is
   201  // nil.
   202  func (r *Resolver) resolveAddrList(ctx context.Context, op, network, addr string, hint Addr) (addrList, error) {
   203  	afnet, _, err := parseNetwork(ctx, network, true)
   204  	if err != nil {
   205  		return nil, err
   206  	}
   207  	if op == "dial" && addr == "" {
   208  		return nil, errMissingAddress
   209  	}
   210  	switch afnet {
   211  	case "unix", "unixgram", "unixpacket":
   212  		addr, err := ResolveUnixAddr(afnet, addr)
   213  		if err != nil {
   214  			return nil, err
   215  		}
   216  		if op == "dial" && hint != nil && addr.Network() != hint.Network() {
   217  			return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()}
   218  		}
   219  		return addrList{addr}, nil
   220  	}
   221  	addrs, err := r.internetAddrList(ctx, afnet, addr)
   222  	if err != nil || op != "dial" || hint == nil {
   223  		return addrs, err
   224  	}
   225  	var (
   226  		tcp      *TCPAddr
   227  		udp      *UDPAddr
   228  		ip       *IPAddr
   229  		wildcard bool
   230  	)
   231  	switch hint := hint.(type) {
   232  	case *TCPAddr:
   233  		tcp = hint
   234  		wildcard = tcp.isWildcard()
   235  	case *UDPAddr:
   236  		udp = hint
   237  		wildcard = udp.isWildcard()
   238  	case *IPAddr:
   239  		ip = hint
   240  		wildcard = ip.isWildcard()
   241  	}
   242  	naddrs := addrs[:0]
   243  	for _, addr := range addrs {
   244  		if addr.Network() != hint.Network() {
   245  			return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()}
   246  		}
   247  		switch addr := addr.(type) {
   248  		case *TCPAddr:
   249  			if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(tcp.IP) {
   250  				continue
   251  			}
   252  			naddrs = append(naddrs, addr)
   253  		case *UDPAddr:
   254  			if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(udp.IP) {
   255  				continue
   256  			}
   257  			naddrs = append(naddrs, addr)
   258  		case *IPAddr:
   259  			if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(ip.IP) {
   260  				continue
   261  			}
   262  			naddrs = append(naddrs, addr)
   263  		}
   264  	}
   265  	if len(naddrs) == 0 {
   266  		return nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: hint.String()}
   267  	}
   268  	return naddrs, nil
   269  }
   270  
   271  // Dial connects to the address on the named network.
   272  //
   273  // Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only),
   274  // "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4"
   275  // (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and
   276  // "unixpacket".
   277  //
   278  // For TCP and UDP networks, the address has the form "host:port".
   279  // The host must be a literal IP address, or a host name that can be
   280  // resolved to IP addresses.
   281  // The port must be a literal port number or a service name.
   282  // If the host is a literal IPv6 address it must be enclosed in square
   283  // brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80".
   284  // The zone specifies the scope of the literal IPv6 address as defined
   285  // in RFC 4007.
   286  // The functions JoinHostPort and SplitHostPort manipulate a pair of
   287  // host and port in this form.
   288  // When using TCP, and the host resolves to multiple IP addresses,
   289  // Dial will try each IP address in order until one succeeds.
   290  //
   291  // Examples:
   292  //	Dial("tcp", "golang.org:http")
   293  //	Dial("tcp", "192.0.2.1:http")
   294  //	Dial("tcp", "198.51.100.1:80")
   295  //	Dial("udp", "[2001:db8::1]:domain")
   296  //	Dial("udp", "[fe80::1%lo0]:53")
   297  //	Dial("tcp", ":80")
   298  //
   299  // For IP networks, the network must be "ip", "ip4" or "ip6" followed
   300  // by a colon and a literal protocol number or a protocol name, and
   301  // the address has the form "host". The host must be a literal IP
   302  // address or a literal IPv6 address with zone.
   303  // It depends on each operating system how the operating system
   304  // behaves with a non-well known protocol number such as "0" or "255".
   305  //
   306  // Examples:
   307  //	Dial("ip4:1", "192.0.2.1")
   308  //	Dial("ip6:ipv6-icmp", "2001:db8::1")
   309  //	Dial("ip6:58", "fe80::1%lo0")
   310  //
   311  // For TCP, UDP and IP networks, if the host is empty or a literal
   312  // unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for
   313  // TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is
   314  // assumed.
   315  //
   316  // For Unix networks, the address must be a file system path.
   317  func Dial(network, address string) (Conn, error) {
   318  	var d Dialer
   319  	return d.Dial(network, address)
   320  }
   321  
   322  // DialTimeout acts like Dial but takes a timeout.
   323  //
   324  // The timeout includes name resolution, if required.
   325  // When using TCP, and the host in the address parameter resolves to
   326  // multiple IP addresses, the timeout is spread over each consecutive
   327  // dial, such that each is given an appropriate fraction of the time
   328  // to connect.
   329  //
   330  // See func Dial for a description of the network and address
   331  // parameters.
   332  func DialTimeout(network, address string, timeout time.Duration) (Conn, error) {
   333  	d := Dialer{Timeout: timeout}
   334  	return d.Dial(network, address)
   335  }
   336  
   337  // sysDialer contains a Dial's parameters and configuration.
   338  type sysDialer struct {
   339  	Dialer
   340  	network, address string
   341  }
   342  
   343  // Dial connects to the address on the named network.
   344  //
   345  // See func Dial for a description of the network and address
   346  // parameters.
   347  func (d *Dialer) Dial(network, address string) (Conn, error) {
   348  	return d.DialContext(context.Background(), network, address)
   349  }
   350  
   351  // DialContext connects to the address on the named network using
   352  // the provided context.
   353  //
   354  // The provided Context must be non-nil. If the context expires before
   355  // the connection is complete, an error is returned. Once successfully
   356  // connected, any expiration of the context will not affect the
   357  // connection.
   358  //
   359  // When using TCP, and the host in the address parameter resolves to multiple
   360  // network addresses, any dial timeout (from d.Timeout or ctx) is spread
   361  // over each consecutive dial, such that each is given an appropriate
   362  // fraction of the time to connect.
   363  // For example, if a host has 4 IP addresses and the timeout is 1 minute,
   364  // the connect to each single address will be given 15 seconds to complete
   365  // before trying the next one.
   366  //
   367  // See func Dial for a description of the network and address
   368  // parameters.
   369  func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error) {
   370  	if ctx == nil {
   371  		panic("nil context")
   372  	}
   373  	deadline := d.deadline(ctx, time.Now())
   374  	if !deadline.IsZero() {
   375  		if d, ok := ctx.Deadline(); !ok || deadline.Before(d) {
   376  			subCtx, cancel := context.WithDeadline(ctx, deadline)
   377  			defer cancel()
   378  			ctx = subCtx
   379  		}
   380  	}
   381  	if oldCancel := d.Cancel; oldCancel != nil {
   382  		subCtx, cancel := context.WithCancel(ctx)
   383  		defer cancel()
   384  		go func() {
   385  			select {
   386  			case <-oldCancel:
   387  				cancel()
   388  			case <-subCtx.Done():
   389  			}
   390  		}()
   391  		ctx = subCtx
   392  	}
   393  
   394  	// Shadow the nettrace (if any) during resolve so Connect events don't fire for DNS lookups.
   395  	resolveCtx := ctx
   396  	if trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace); trace != nil {
   397  		shadow := *trace
   398  		shadow.ConnectStart = nil
   399  		shadow.ConnectDone = nil
   400  		resolveCtx = context.WithValue(resolveCtx, nettrace.TraceKey{}, &shadow)
   401  	}
   402  
   403  	addrs, err := d.resolver().resolveAddrList(resolveCtx, "dial", network, address, d.LocalAddr)
   404  	if err != nil {
   405  		return nil, &OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: err}
   406  	}
   407  
   408  	sd := &sysDialer{
   409  		Dialer:  *d,
   410  		network: network,
   411  		address: address,
   412  	}
   413  
   414  	var primaries, fallbacks addrList
   415  	if d.dualStack() && network == "tcp" {
   416  		primaries, fallbacks = addrs.partition(isIPv4)
   417  	} else {
   418  		primaries = addrs
   419  	}
   420  
   421  	var c Conn
   422  	if len(fallbacks) > 0 {
   423  		c, err = sd.dialParallel(ctx, primaries, fallbacks)
   424  	} else {
   425  		c, err = sd.dialSerial(ctx, primaries)
   426  	}
   427  	if err != nil {
   428  		return nil, err
   429  	}
   430  
   431  	if tc, ok := c.(*TCPConn); ok && d.KeepAlive >= 0 {
   432  		setKeepAlive(tc.fd, true)
   433  		ka := d.KeepAlive
   434  		if d.KeepAlive == 0 {
   435  			ka = defaultTCPKeepAlive
   436  		}
   437  		setKeepAlivePeriod(tc.fd, ka)
   438  		testHookSetKeepAlive(ka)
   439  	}
   440  	return c, nil
   441  }
   442  
   443  // dialParallel races two copies of dialSerial, giving the first a
   444  // head start. It returns the first established connection and
   445  // closes the others. Otherwise it returns an error from the first
   446  // primary address.
   447  func (sd *sysDialer) dialParallel(ctx context.Context, primaries, fallbacks addrList) (Conn, error) {
   448  	if len(fallbacks) == 0 {
   449  		return sd.dialSerial(ctx, primaries)
   450  	}
   451  
   452  	returned := make(chan struct{})
   453  	defer close(returned)
   454  
   455  	type dialResult struct {
   456  		Conn
   457  		error
   458  		primary bool
   459  		done    bool
   460  	}
   461  	results := make(chan dialResult) // unbuffered
   462  
   463  	startRacer := func(ctx context.Context, primary bool) {
   464  		ras := primaries
   465  		if !primary {
   466  			ras = fallbacks
   467  		}
   468  		c, err := sd.dialSerial(ctx, ras)
   469  		select {
   470  		case results <- dialResult{Conn: c, error: err, primary: primary, done: true}:
   471  		case <-returned:
   472  			if c != nil {
   473  				c.Close()
   474  			}
   475  		}
   476  	}
   477  
   478  	var primary, fallback dialResult
   479  
   480  	// Start the main racer.
   481  	primaryCtx, primaryCancel := context.WithCancel(ctx)
   482  	defer primaryCancel()
   483  	go startRacer(primaryCtx, true)
   484  
   485  	// Start the timer for the fallback racer.
   486  	fallbackTimer := time.NewTimer(sd.fallbackDelay())
   487  	defer fallbackTimer.Stop()
   488  
   489  	for {
   490  		select {
   491  		case <-fallbackTimer.C:
   492  			fallbackCtx, fallbackCancel := context.WithCancel(ctx)
   493  			defer fallbackCancel()
   494  			go startRacer(fallbackCtx, false)
   495  
   496  		case res := <-results:
   497  			if res.error == nil {
   498  				return res.Conn, nil
   499  			}
   500  			if res.primary {
   501  				primary = res
   502  			} else {
   503  				fallback = res
   504  			}
   505  			if primary.done && fallback.done {
   506  				return nil, primary.error
   507  			}
   508  			if res.primary && fallbackTimer.Stop() {
   509  				// If we were able to stop the timer, that means it
   510  				// was running (hadn't yet started the fallback), but
   511  				// we just got an error on the primary path, so start
   512  				// the fallback immediately (in 0 nanoseconds).
   513  				fallbackTimer.Reset(0)
   514  			}
   515  		}
   516  	}
   517  }
   518  
   519  // dialSerial connects to a list of addresses in sequence, returning
   520  // either the first successful connection, or the first error.
   521  func (sd *sysDialer) dialSerial(ctx context.Context, ras addrList) (Conn, error) {
   522  	var firstErr error // The error from the first address is most relevant.
   523  
   524  	for i, ra := range ras {
   525  		select {
   526  		case <-ctx.Done():
   527  			return nil, &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: mapErr(ctx.Err())}
   528  		default:
   529  		}
   530  
   531  		dialCtx := ctx
   532  		if deadline, hasDeadline := ctx.Deadline(); hasDeadline {
   533  			partialDeadline, err := partialDeadline(time.Now(), deadline, len(ras)-i)
   534  			if err != nil {
   535  				// Ran out of time.
   536  				if firstErr == nil {
   537  					firstErr = &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: err}
   538  				}
   539  				break
   540  			}
   541  			if partialDeadline.Before(deadline) {
   542  				var cancel context.CancelFunc
   543  				dialCtx, cancel = context.WithDeadline(ctx, partialDeadline)
   544  				defer cancel()
   545  			}
   546  		}
   547  
   548  		c, err := sd.dialSingle(dialCtx, ra)
   549  		if err == nil {
   550  			return c, nil
   551  		}
   552  		if firstErr == nil {
   553  			firstErr = err
   554  		}
   555  	}
   556  
   557  	if firstErr == nil {
   558  		firstErr = &OpError{Op: "dial", Net: sd.network, Source: nil, Addr: nil, Err: errMissingAddress}
   559  	}
   560  	return nil, firstErr
   561  }
   562  
   563  // dialSingle attempts to establish and returns a single connection to
   564  // the destination address.
   565  func (sd *sysDialer) dialSingle(ctx context.Context, ra Addr) (c Conn, err error) {
   566  	trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace)
   567  	if trace != nil {
   568  		raStr := ra.String()
   569  		if trace.ConnectStart != nil {
   570  			trace.ConnectStart(sd.network, raStr)
   571  		}
   572  		if trace.ConnectDone != nil {
   573  			defer func() { trace.ConnectDone(sd.network, raStr, err) }()
   574  		}
   575  	}
   576  	la := sd.LocalAddr
   577  	switch ra := ra.(type) {
   578  	case *TCPAddr:
   579  		la, _ := la.(*TCPAddr)
   580  		c, err = sd.dialTCP(ctx, la, ra)
   581  	case *UDPAddr:
   582  		la, _ := la.(*UDPAddr)
   583  		c, err = sd.dialUDP(ctx, la, ra)
   584  	case *IPAddr:
   585  		la, _ := la.(*IPAddr)
   586  		c, err = sd.dialIP(ctx, la, ra)
   587  	case *UnixAddr:
   588  		la, _ := la.(*UnixAddr)
   589  		c, err = sd.dialUnix(ctx, la, ra)
   590  	default:
   591  		return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: &AddrError{Err: "unexpected address type", Addr: sd.address}}
   592  	}
   593  	if err != nil {
   594  		return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: err} // c is non-nil interface containing nil pointer
   595  	}
   596  	return c, nil
   597  }
   598  
   599  // ListenConfig contains options for listening to an address.
   600  type ListenConfig struct {
   601  	// If Control is not nil, it is called after creating the network
   602  	// connection but before binding it to the operating system.
   603  	//
   604  	// Network and address parameters passed to Control method are not
   605  	// necessarily the ones passed to Listen. For example, passing "tcp" to
   606  	// Listen will cause the Control function to be called with "tcp4" or "tcp6".
   607  	Control func(network, address string, c syscall.RawConn) error
   608  
   609  	// KeepAlive specifies the keep-alive period for network
   610  	// connections accepted by this listener.
   611  	// If zero, keep-alives are enabled if supported by the protocol
   612  	// and operating system. Network protocols or operating systems
   613  	// that do not support keep-alives ignore this field.
   614  	// If negative, keep-alives are disabled.
   615  	KeepAlive time.Duration
   616  }
   617  
   618  // Listen announces on the local network address.
   619  //
   620  // See func Listen for a description of the network and address
   621  // parameters.
   622  func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error) {
   623  	addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil)
   624  	if err != nil {
   625  		return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err}
   626  	}
   627  	sl := &sysListener{
   628  		ListenConfig: *lc,
   629  		network:      network,
   630  		address:      address,
   631  	}
   632  	var l Listener
   633  	la := addrs.first(isIPv4)
   634  	switch la := la.(type) {
   635  	case *TCPAddr:
   636  		l, err = sl.listenTCP(ctx, la)
   637  	case *UnixAddr:
   638  		l, err = sl.listenUnix(ctx, la)
   639  	default:
   640  		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}}
   641  	}
   642  	if err != nil {
   643  		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // l is non-nil interface containing nil pointer
   644  	}
   645  	return l, nil
   646  }
   647  
   648  // ListenPacket announces on the local network address.
   649  //
   650  // See func ListenPacket for a description of the network and address
   651  // parameters.
   652  func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error) {
   653  	addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil)
   654  	if err != nil {
   655  		return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err}
   656  	}
   657  	sl := &sysListener{
   658  		ListenConfig: *lc,
   659  		network:      network,
   660  		address:      address,
   661  	}
   662  	var c PacketConn
   663  	la := addrs.first(isIPv4)
   664  	switch la := la.(type) {
   665  	case *UDPAddr:
   666  		c, err = sl.listenUDP(ctx, la)
   667  	case *IPAddr:
   668  		c, err = sl.listenIP(ctx, la)
   669  	case *UnixAddr:
   670  		c, err = sl.listenUnixgram(ctx, la)
   671  	default:
   672  		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}}
   673  	}
   674  	if err != nil {
   675  		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // c is non-nil interface containing nil pointer
   676  	}
   677  	return c, nil
   678  }
   679  
   680  // sysListener contains a Listen's parameters and configuration.
   681  type sysListener struct {
   682  	ListenConfig
   683  	network, address string
   684  }
   685  
   686  // Listen announces on the local network address.
   687  //
   688  // The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket".
   689  //
   690  // For TCP networks, if the host in the address parameter is empty or
   691  // a literal unspecified IP address, Listen listens on all available
   692  // unicast and anycast IP addresses of the local system.
   693  // To only use IPv4, use network "tcp4".
   694  // The address can use a host name, but this is not recommended,
   695  // because it will create a listener for at most one of the host's IP
   696  // addresses.
   697  // If the port in the address parameter is empty or "0", as in
   698  // "127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
   699  // The Addr method of Listener can be used to discover the chosen
   700  // port.
   701  //
   702  // See func Dial for a description of the network and address
   703  // parameters.
   704  func Listen(network, address string) (Listener, error) {
   705  	var lc ListenConfig
   706  	return lc.Listen(context.Background(), network, address)
   707  }
   708  
   709  // ListenPacket announces on the local network address.
   710  //
   711  // The network must be "udp", "udp4", "udp6", "unixgram", or an IP
   712  // transport. The IP transports are "ip", "ip4", or "ip6" followed by
   713  // a colon and a literal protocol number or a protocol name, as in
   714  // "ip:1" or "ip:icmp".
   715  //
   716  // For UDP and IP networks, if the host in the address parameter is
   717  // empty or a literal unspecified IP address, ListenPacket listens on
   718  // all available IP addresses of the local system except multicast IP
   719  // addresses.
   720  // To only use IPv4, use network "udp4" or "ip4:proto".
   721  // The address can use a host name, but this is not recommended,
   722  // because it will create a listener for at most one of the host's IP
   723  // addresses.
   724  // If the port in the address parameter is empty or "0", as in
   725  // "127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
   726  // The LocalAddr method of PacketConn can be used to discover the
   727  // chosen port.
   728  //
   729  // See func Dial for a description of the network and address
   730  // parameters.
   731  func ListenPacket(network, address string) (PacketConn, error) {
   732  	var lc ListenConfig
   733  	return lc.ListenPacket(context.Background(), network, address)
   734  }
   735  

View as plain text