rsc.io/go@v0.0.0-20150416155037-e040fd465409/src/net/tcpsock_posix.go (about)

     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  // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris windows
     6  
     7  package net
     8  
     9  import (
    10  	"io"
    11  	"os"
    12  	"syscall"
    13  	"time"
    14  )
    15  
    16  // BUG(rsc): On OpenBSD, listening on the "tcp" network does not listen for
    17  // both IPv4 and IPv6 connections. This is due to the fact that IPv4 traffic
    18  // will not be routed to an IPv6 socket - two separate sockets are required
    19  // if both AFs are to be supported. See inet6(4) on OpenBSD for details.
    20  
    21  func sockaddrToTCP(sa syscall.Sockaddr) Addr {
    22  	switch sa := sa.(type) {
    23  	case *syscall.SockaddrInet4:
    24  		return &TCPAddr{IP: sa.Addr[0:], Port: sa.Port}
    25  	case *syscall.SockaddrInet6:
    26  		return &TCPAddr{IP: sa.Addr[0:], Port: sa.Port, Zone: zoneToString(int(sa.ZoneId))}
    27  	}
    28  	return nil
    29  }
    30  
    31  func (a *TCPAddr) family() int {
    32  	if a == nil || len(a.IP) <= IPv4len {
    33  		return syscall.AF_INET
    34  	}
    35  	if a.IP.To4() != nil {
    36  		return syscall.AF_INET
    37  	}
    38  	return syscall.AF_INET6
    39  }
    40  
    41  func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, error) {
    42  	if a == nil {
    43  		return nil, nil
    44  	}
    45  	return ipToSockaddr(family, a.IP, a.Port, a.Zone)
    46  }
    47  
    48  // TCPConn is an implementation of the Conn interface for TCP network
    49  // connections.
    50  type TCPConn struct {
    51  	conn
    52  }
    53  
    54  func newTCPConn(fd *netFD) *TCPConn {
    55  	c := &TCPConn{conn{fd}}
    56  	c.SetNoDelay(true)
    57  	return c
    58  }
    59  
    60  // ReadFrom implements the io.ReaderFrom ReadFrom method.
    61  func (c *TCPConn) ReadFrom(r io.Reader) (int64, error) {
    62  	if n, err, handled := sendFile(c.fd, r); handled {
    63  		return n, err
    64  	}
    65  	return genericReadFrom(c, r)
    66  }
    67  
    68  // CloseRead shuts down the reading side of the TCP connection.
    69  // Most callers should just use Close.
    70  func (c *TCPConn) CloseRead() error {
    71  	if !c.ok() {
    72  		return syscall.EINVAL
    73  	}
    74  	return c.fd.closeRead()
    75  }
    76  
    77  // CloseWrite shuts down the writing side of the TCP connection.
    78  // Most callers should just use Close.
    79  func (c *TCPConn) CloseWrite() error {
    80  	if !c.ok() {
    81  		return syscall.EINVAL
    82  	}
    83  	return c.fd.closeWrite()
    84  }
    85  
    86  // SetLinger sets the behavior of Close on a connection which still
    87  // has data waiting to be sent or to be acknowledged.
    88  //
    89  // If sec < 0 (the default), the operating system finishes sending the
    90  // data in the background.
    91  //
    92  // If sec == 0, the operating system discards any unsent or
    93  // unacknowledged data.
    94  //
    95  // If sec > 0, the data is sent in the background as with sec < 0. On
    96  // some operating systems after sec seconds have elapsed any remaining
    97  // unsent data may be discarded.
    98  func (c *TCPConn) SetLinger(sec int) error {
    99  	if !c.ok() {
   100  		return syscall.EINVAL
   101  	}
   102  	return setLinger(c.fd, sec)
   103  }
   104  
   105  // SetKeepAlive sets whether the operating system should send
   106  // keepalive messages on the connection.
   107  func (c *TCPConn) SetKeepAlive(keepalive bool) error {
   108  	if !c.ok() {
   109  		return syscall.EINVAL
   110  	}
   111  	return setKeepAlive(c.fd, keepalive)
   112  }
   113  
   114  // SetKeepAlivePeriod sets period between keep alives.
   115  func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error {
   116  	if !c.ok() {
   117  		return syscall.EINVAL
   118  	}
   119  	return setKeepAlivePeriod(c.fd, d)
   120  }
   121  
   122  // SetNoDelay controls whether the operating system should delay
   123  // packet transmission in hopes of sending fewer packets (Nagle's
   124  // algorithm).  The default is true (no delay), meaning that data is
   125  // sent as soon as possible after a Write.
   126  func (c *TCPConn) SetNoDelay(noDelay bool) error {
   127  	if !c.ok() {
   128  		return syscall.EINVAL
   129  	}
   130  	return setNoDelay(c.fd, noDelay)
   131  }
   132  
   133  // DialTCP connects to the remote address raddr on the network net,
   134  // which must be "tcp", "tcp4", or "tcp6".  If laddr is not nil, it is
   135  // used as the local address for the connection.
   136  func DialTCP(net string, laddr, raddr *TCPAddr) (*TCPConn, error) {
   137  	switch net {
   138  	case "tcp", "tcp4", "tcp6":
   139  	default:
   140  		return nil, &OpError{Op: "dial", Net: net, Addr: raddr, Err: UnknownNetworkError(net)}
   141  	}
   142  	if raddr == nil {
   143  		return nil, &OpError{Op: "dial", Net: net, Addr: nil, Err: errMissingAddress}
   144  	}
   145  	return dialTCP(net, laddr, raddr, noDeadline)
   146  }
   147  
   148  func dialTCP(net string, laddr, raddr *TCPAddr, deadline time.Time) (*TCPConn, error) {
   149  	fd, err := internetSocket(net, laddr, raddr, deadline, syscall.SOCK_STREAM, 0, "dial")
   150  
   151  	// TCP has a rarely used mechanism called a 'simultaneous connection' in
   152  	// which Dial("tcp", addr1, addr2) run on the machine at addr1 can
   153  	// connect to a simultaneous Dial("tcp", addr2, addr1) run on the machine
   154  	// at addr2, without either machine executing Listen.  If laddr == nil,
   155  	// it means we want the kernel to pick an appropriate originating local
   156  	// address.  Some Linux kernels cycle blindly through a fixed range of
   157  	// local ports, regardless of destination port.  If a kernel happens to
   158  	// pick local port 50001 as the source for a Dial("tcp", "", "localhost:50001"),
   159  	// then the Dial will succeed, having simultaneously connected to itself.
   160  	// This can only happen when we are letting the kernel pick a port (laddr == nil)
   161  	// and when there is no listener for the destination address.
   162  	// It's hard to argue this is anything other than a kernel bug.  If we
   163  	// see this happen, rather than expose the buggy effect to users, we
   164  	// close the fd and try again.  If it happens twice more, we relent and
   165  	// use the result.  See also:
   166  	//	http://golang.org/issue/2690
   167  	//	http://stackoverflow.com/questions/4949858/
   168  	//
   169  	// The opposite can also happen: if we ask the kernel to pick an appropriate
   170  	// originating local address, sometimes it picks one that is already in use.
   171  	// So if the error is EADDRNOTAVAIL, we have to try again too, just for
   172  	// a different reason.
   173  	//
   174  	// The kernel socket code is no doubt enjoying watching us squirm.
   175  	for i := 0; i < 2 && (laddr == nil || laddr.Port == 0) && (selfConnect(fd, err) || spuriousENOTAVAIL(err)); i++ {
   176  		if err == nil {
   177  			fd.Close()
   178  		}
   179  		fd, err = internetSocket(net, laddr, raddr, deadline, syscall.SOCK_STREAM, 0, "dial")
   180  	}
   181  
   182  	if err != nil {
   183  		return nil, &OpError{Op: "dial", Net: net, Addr: raddr, Err: err}
   184  	}
   185  	return newTCPConn(fd), nil
   186  }
   187  
   188  func selfConnect(fd *netFD, err error) bool {
   189  	// If the connect failed, we clearly didn't connect to ourselves.
   190  	if err != nil {
   191  		return false
   192  	}
   193  
   194  	// The socket constructor can return an fd with raddr nil under certain
   195  	// unknown conditions. The errors in the calls there to Getpeername
   196  	// are discarded, but we can't catch the problem there because those
   197  	// calls are sometimes legally erroneous with a "socket not connected".
   198  	// Since this code (selfConnect) is already trying to work around
   199  	// a problem, we make sure if this happens we recognize trouble and
   200  	// ask the DialTCP routine to try again.
   201  	// TODO: try to understand what's really going on.
   202  	if fd.laddr == nil || fd.raddr == nil {
   203  		return true
   204  	}
   205  	l := fd.laddr.(*TCPAddr)
   206  	r := fd.raddr.(*TCPAddr)
   207  	return l.Port == r.Port && l.IP.Equal(r.IP)
   208  }
   209  
   210  func spuriousENOTAVAIL(err error) bool {
   211  	e, ok := err.(*OpError)
   212  	return ok && e.Err == syscall.EADDRNOTAVAIL
   213  }
   214  
   215  // TCPListener is a TCP network listener.  Clients should typically
   216  // use variables of type Listener instead of assuming TCP.
   217  type TCPListener struct {
   218  	fd *netFD
   219  }
   220  
   221  // AcceptTCP accepts the next incoming call and returns the new
   222  // connection.
   223  func (l *TCPListener) AcceptTCP() (*TCPConn, error) {
   224  	if l == nil || l.fd == nil {
   225  		return nil, syscall.EINVAL
   226  	}
   227  	fd, err := l.fd.accept()
   228  	if err != nil {
   229  		return nil, err
   230  	}
   231  	return newTCPConn(fd), nil
   232  }
   233  
   234  // Accept implements the Accept method in the Listener interface; it
   235  // waits for the next call and returns a generic Conn.
   236  func (l *TCPListener) Accept() (Conn, error) {
   237  	c, err := l.AcceptTCP()
   238  	if err != nil {
   239  		return nil, err
   240  	}
   241  	return c, nil
   242  }
   243  
   244  // Close stops listening on the TCP address.
   245  // Already Accepted connections are not closed.
   246  func (l *TCPListener) Close() error {
   247  	if l == nil || l.fd == nil {
   248  		return syscall.EINVAL
   249  	}
   250  	return l.fd.Close()
   251  }
   252  
   253  // Addr returns the listener's network address, a *TCPAddr.
   254  // The Addr returned is shared by all invocations of Addr, so
   255  // do not modify it.
   256  func (l *TCPListener) Addr() Addr { return l.fd.laddr }
   257  
   258  // SetDeadline sets the deadline associated with the listener.
   259  // A zero time value disables the deadline.
   260  func (l *TCPListener) SetDeadline(t time.Time) error {
   261  	if l == nil || l.fd == nil {
   262  		return syscall.EINVAL
   263  	}
   264  	return l.fd.setDeadline(t)
   265  }
   266  
   267  // File returns a copy of the underlying os.File, set to blocking
   268  // mode.  It is the caller's responsibility to close f when finished.
   269  // Closing l does not affect f, and closing f does not affect l.
   270  //
   271  // The returned os.File's file descriptor is different from the
   272  // connection's.  Attempting to change properties of the original
   273  // using this duplicate may or may not have the desired effect.
   274  func (l *TCPListener) File() (f *os.File, err error) { return l.fd.dup() }
   275  
   276  // ListenTCP announces on the TCP address laddr and returns a TCP
   277  // listener.  Net must be "tcp", "tcp4", or "tcp6".  If laddr has a
   278  // port of 0, ListenTCP will choose an available port.  The caller can
   279  // use the Addr method of TCPListener to retrieve the chosen address.
   280  func ListenTCP(net string, laddr *TCPAddr) (*TCPListener, error) {
   281  	switch net {
   282  	case "tcp", "tcp4", "tcp6":
   283  	default:
   284  		return nil, &OpError{Op: "listen", Net: net, Addr: laddr, Err: UnknownNetworkError(net)}
   285  	}
   286  	if laddr == nil {
   287  		laddr = &TCPAddr{}
   288  	}
   289  	fd, err := internetSocket(net, laddr, nil, noDeadline, syscall.SOCK_STREAM, 0, "listen")
   290  	if err != nil {
   291  		return nil, &OpError{Op: "listen", Net: net, Addr: laddr, Err: err}
   292  	}
   293  	return &TCPListener{fd}, nil
   294  }