Home | History | Annotate | Download | only in 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 // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris 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 := sendFile(c.fd, r); handled {
     49 		return n, err
     50 	}
     51 	return genericReadFrom(c, r)
     52 }
     53 
     54 func dialTCP(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, error) {
     55 	if testHookDialTCP != nil {
     56 		return testHookDialTCP(ctx, net, laddr, raddr)
     57 	}
     58 	return doDialTCP(ctx, net, laddr, raddr)
     59 }
     60 
     61 func doDialTCP(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, error) {
     62 	fd, err := internetSocket(ctx, net, laddr, raddr, syscall.SOCK_STREAM, 0, "dial")
     63 
     64 	// TCP has a rarely used mechanism called a 'simultaneous connection' in
     65 	// which Dial("tcp", addr1, addr2) run on the machine at addr1 can
     66 	// connect to a simultaneous Dial("tcp", addr2, addr1) run on the machine
     67 	// at addr2, without either machine executing Listen. If laddr == nil,
     68 	// it means we want the kernel to pick an appropriate originating local
     69 	// address. Some Linux kernels cycle blindly through a fixed range of
     70 	// local ports, regardless of destination port. If a kernel happens to
     71 	// pick local port 50001 as the source for a Dial("tcp", "", "localhost:50001"),
     72 	// then the Dial will succeed, having simultaneously connected to itself.
     73 	// This can only happen when we are letting the kernel pick a port (laddr == nil)
     74 	// and when there is no listener for the destination address.
     75 	// It's hard to argue this is anything other than a kernel bug. If we
     76 	// see this happen, rather than expose the buggy effect to users, we
     77 	// close the fd and try again. If it happens twice more, we relent and
     78 	// use the result. See also:
     79 	//	https://golang.org/issue/2690
     80 	//	http://stackoverflow.com/questions/4949858/
     81 	//
     82 	// The opposite can also happen: if we ask the kernel to pick an appropriate
     83 	// originating local address, sometimes it picks one that is already in use.
     84 	// So if the error is EADDRNOTAVAIL, we have to try again too, just for
     85 	// a different reason.
     86 	//
     87 	// The kernel socket code is no doubt enjoying watching us squirm.
     88 	for i := 0; i < 2 && (laddr == nil || laddr.Port == 0) && (selfConnect(fd, err) || spuriousENOTAVAIL(err)); i++ {
     89 		if err == nil {
     90 			fd.Close()
     91 		}
     92 		fd, err = internetSocket(ctx, net, laddr, raddr, syscall.SOCK_STREAM, 0, "dial")
     93 	}
     94 
     95 	if err != nil {
     96 		return nil, err
     97 	}
     98 	return newTCPConn(fd), nil
     99 }
    100 
    101 func selfConnect(fd *netFD, err error) bool {
    102 	// If the connect failed, we clearly didn't connect to ourselves.
    103 	if err != nil {
    104 		return false
    105 	}
    106 
    107 	// The socket constructor can return an fd with raddr nil under certain
    108 	// unknown conditions. The errors in the calls there to Getpeername
    109 	// are discarded, but we can't catch the problem there because those
    110 	// calls are sometimes legally erroneous with a "socket not connected".
    111 	// Since this code (selfConnect) is already trying to work around
    112 	// a problem, we make sure if this happens we recognize trouble and
    113 	// ask the DialTCP routine to try again.
    114 	// TODO: try to understand what's really going on.
    115 	if fd.laddr == nil || fd.raddr == nil {
    116 		return true
    117 	}
    118 	l := fd.laddr.(*TCPAddr)
    119 	r := fd.raddr.(*TCPAddr)
    120 	return l.Port == r.Port && l.IP.Equal(r.IP)
    121 }
    122 
    123 func spuriousENOTAVAIL(err error) bool {
    124 	if op, ok := err.(*OpError); ok {
    125 		err = op.Err
    126 	}
    127 	if sys, ok := err.(*os.SyscallError); ok {
    128 		err = sys.Err
    129 	}
    130 	return err == syscall.EADDRNOTAVAIL
    131 }
    132 
    133 func (ln *TCPListener) ok() bool { return ln != nil && ln.fd != nil }
    134 
    135 func (ln *TCPListener) accept() (*TCPConn, error) {
    136 	fd, err := ln.fd.accept()
    137 	if err != nil {
    138 		return nil, err
    139 	}
    140 	return newTCPConn(fd), nil
    141 }
    142 
    143 func (ln *TCPListener) close() error {
    144 	return ln.fd.Close()
    145 }
    146 
    147 func (ln *TCPListener) file() (*os.File, error) {
    148 	f, err := ln.fd.dup()
    149 	if err != nil {
    150 		return nil, err
    151 	}
    152 	return f, nil
    153 }
    154 
    155 func listenTCP(ctx context.Context, network string, laddr *TCPAddr) (*TCPListener, error) {
    156 	fd, err := internetSocket(ctx, network, laddr, nil, syscall.SOCK_STREAM, 0, "listen")
    157 	if err != nil {
    158 		return nil, err
    159 	}
    160 	return &TCPListener{fd}, nil
    161 }
    162