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

View as plain text