Black Lives Matter. Support the Equal Justice Initiative.

Source file src/net/tcpsock_posix.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  //go:build aix || darwin || dragonfly || freebsd || (js && wasm) || linux || netbsd || openbsd || solaris || windows
     6  // +build aix darwin dragonfly freebsd js,wasm linux netbsd openbsd solaris windows
     7  
     8  package net
     9  
    10  import (
    11  	"context"
    12  	"io"
    13  	"os"
    14  	"syscall"
    15  )
    16  
    17  func sockaddrToTCP(sa syscall.Sockaddr) Addr {
    18  	switch sa := sa.(type) {
    19  	case *syscall.SockaddrInet4:
    20  		return &TCPAddr{IP: sa.Addr[0:], Port: sa.Port}
    21  	case *syscall.SockaddrInet6:
    22  		return &TCPAddr{IP: sa.Addr[0:], Port: sa.Port, Zone: zoneCache.name(int(sa.ZoneId))}
    23  	}
    24  	return nil
    25  }
    26  
    27  func (a *TCPAddr) family() int {
    28  	if a == nil || len(a.IP) <= IPv4len {
    29  		return syscall.AF_INET
    30  	}
    31  	if a.IP.To4() != nil {
    32  		return syscall.AF_INET
    33  	}
    34  	return syscall.AF_INET6
    35  }
    36  
    37  func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, error) {
    38  	if a == nil {
    39  		return nil, nil
    40  	}
    41  	return ipToSockaddr(family, a.IP, a.Port, a.Zone)
    42  }
    43  
    44  func (a *TCPAddr) toLocal(net string) sockaddr {
    45  	return &TCPAddr{loopbackIP(net), a.Port, a.Zone}
    46  }
    47  
    48  func (c *TCPConn) readFrom(r io.Reader) (int64, error) {
    49  	if n, err, handled := splice(c.fd, r); handled {
    50  		return n, err
    51  	}
    52  	if n, err, handled := sendFile(c.fd, r); handled {
    53  		return n, err
    54  	}
    55  	return genericReadFrom(c, r)
    56  }
    57  
    58  func (sd *sysDialer) dialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) {
    59  	if testHookDialTCP != nil {
    60  		return testHookDialTCP(ctx, sd.network, laddr, raddr)
    61  	}
    62  	return sd.doDialTCP(ctx, laddr, raddr)
    63  }
    64  
    65  func (sd *sysDialer) doDialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) {
    66  	fd, err := internetSocket(ctx, sd.network, laddr, raddr, syscall.SOCK_STREAM, 0, "dial", sd.Dialer.Control)
    67  
    68  	// TCP has a rarely used mechanism called a 'simultaneous connection' in
    69  	// which Dial("tcp", addr1, addr2) run on the machine at addr1 can
    70  	// connect to a simultaneous Dial("tcp", addr2, addr1) run on the machine
    71  	// at addr2, without either machine executing Listen. If laddr == nil,
    72  	// it means we want the kernel to pick an appropriate originating local
    73  	// address. Some Linux kernels cycle blindly through a fixed range of
    74  	// local ports, regardless of destination port. If a kernel happens to
    75  	// pick local port 50001 as the source for a Dial("tcp", "", "localhost:50001"),
    76  	// then the Dial will succeed, having simultaneously connected to itself.
    77  	// This can only happen when we are letting the kernel pick a port (laddr == nil)
    78  	// and when there is no listener for the destination address.
    79  	// It's hard to argue this is anything other than a kernel bug. If we
    80  	// see this happen, rather than expose the buggy effect to users, we
    81  	// close the fd and try again. If it happens twice more, we relent and
    82  	// use the result. See also:
    83  	//	https://golang.org/issue/2690
    84  	//	https://stackoverflow.com/questions/4949858/
    85  	//
    86  	// The opposite can also happen: if we ask the kernel to pick an appropriate
    87  	// originating local address, sometimes it picks one that is already in use.
    88  	// So if the error is EADDRNOTAVAIL, we have to try again too, just for
    89  	// a different reason.
    90  	//
    91  	// The kernel socket code is no doubt enjoying watching us squirm.
    92  	for i := 0; i < 2 && (laddr == nil || laddr.Port == 0) && (selfConnect(fd, err) || spuriousENOTAVAIL(err)); i++ {
    93  		if err == nil {
    94  			fd.Close()
    95  		}
    96  		fd, err = internetSocket(ctx, sd.network, laddr, raddr, syscall.SOCK_STREAM, 0, "dial", sd.Dialer.Control)
    97  	}
    98  
    99  	if err != nil {
   100  		return nil, err
   101  	}
   102  	return newTCPConn(fd), nil
   103  }
   104  
   105  func selfConnect(fd *netFD, err error) bool {
   106  	// If the connect failed, we clearly didn't connect to ourselves.
   107  	if err != nil {
   108  		return false
   109  	}
   110  
   111  	// The socket constructor can return an fd with raddr nil under certain
   112  	// unknown conditions. The errors in the calls there to Getpeername
   113  	// are discarded, but we can't catch the problem there because those
   114  	// calls are sometimes legally erroneous with a "socket not connected".
   115  	// Since this code (selfConnect) is already trying to work around
   116  	// a problem, we make sure if this happens we recognize trouble and
   117  	// ask the DialTCP routine to try again.
   118  	// TODO: try to understand what's really going on.
   119  	if fd.laddr == nil || fd.raddr == nil {
   120  		return true
   121  	}
   122  	l := fd.laddr.(*TCPAddr)
   123  	r := fd.raddr.(*TCPAddr)
   124  	return l.Port == r.Port && l.IP.Equal(r.IP)
   125  }
   126  
   127  func spuriousENOTAVAIL(err error) bool {
   128  	if op, ok := err.(*OpError); ok {
   129  		err = op.Err
   130  	}
   131  	if sys, ok := err.(*os.SyscallError); ok {
   132  		err = sys.Err
   133  	}
   134  	return err == syscall.EADDRNOTAVAIL
   135  }
   136  
   137  func (ln *TCPListener) ok() bool { return ln != nil && ln.fd != nil }
   138  
   139  func (ln *TCPListener) accept() (*TCPConn, error) {
   140  	fd, err := ln.fd.accept()
   141  	if err != nil {
   142  		return nil, err
   143  	}
   144  	tc := newTCPConn(fd)
   145  	if ln.lc.KeepAlive >= 0 {
   146  		setKeepAlive(fd, true)
   147  		ka := ln.lc.KeepAlive
   148  		if ln.lc.KeepAlive == 0 {
   149  			ka = defaultTCPKeepAlive
   150  		}
   151  		setKeepAlivePeriod(fd, ka)
   152  	}
   153  	return tc, nil
   154  }
   155  
   156  func (ln *TCPListener) close() error {
   157  	return ln.fd.Close()
   158  }
   159  
   160  func (ln *TCPListener) file() (*os.File, error) {
   161  	f, err := ln.fd.dup()
   162  	if err != nil {
   163  		return nil, err
   164  	}
   165  	return f, nil
   166  }
   167  
   168  func (sl *sysListener) listenTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error) {
   169  	fd, err := internetSocket(ctx, sl.network, laddr, nil, syscall.SOCK_STREAM, 0, "listen", sl.ListenConfig.Control)
   170  	if err != nil {
   171  		return nil, err
   172  	}
   173  	return &TCPListener{fd: fd, lc: sl.ListenConfig}, nil
   174  }
   175  

View as plain text