tcpsock.mx raw

   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  package net
   6  
   7  import (
   8  	"context"
   9  	"internal/itoa"
  10  	"io"
  11  	"net/netip"
  12  	"os"
  13  	"syscall"
  14  	"time"
  15  )
  16  
  17  // BUG(mikio): On JS, the File method of TCPConn and
  18  // TCPListener is not implemented.
  19  
  20  // TCPAddr represents the address of a TCP end point.
  21  type TCPAddr struct {
  22  	IP   IP
  23  	Port int
  24  	Zone []byte // IPv6 scoped addressing zone
  25  }
  26  
  27  // AddrPort returns the [TCPAddr] a as a [netip.AddrPort].
  28  //
  29  // If a.Port does not fit in a uint16, it's silently truncated.
  30  //
  31  // If a is nil, a zero value is returned.
  32  func (a *TCPAddr) AddrPort() netip.AddrPort {
  33  	if a == nil {
  34  		return netip.AddrPort{}
  35  	}
  36  	na, _ := netip.AddrFromSlice(a.IP)
  37  	na = na.WithZone(a.Zone)
  38  	return netip.AddrPortFrom(na, uint16(a.Port))
  39  }
  40  
  41  // Network returns the address's network name, "tcp".
  42  func (a *TCPAddr) Network() []byte { return "tcp" }
  43  
  44  func (a *TCPAddr) String() string {
  45  	if a == nil {
  46  		return "<nil>"
  47  	}
  48  	ip := ipEmptyString(a.IP)
  49  	if a.Zone != "" {
  50  		return JoinHostPort(ip+"%"+a.Zone, itoa.Itoa(a.Port))
  51  	}
  52  	return JoinHostPort(ip, itoa.Itoa(a.Port))
  53  }
  54  
  55  func (a *TCPAddr) isWildcard() bool {
  56  	if a == nil || a.IP == nil {
  57  		return true
  58  	}
  59  	return a.IP.IsUnspecified()
  60  }
  61  
  62  func (a *TCPAddr) opAddr() Addr {
  63  	if a == nil {
  64  		return nil
  65  	}
  66  	return a
  67  }
  68  
  69  // ResolveTCPAddr returns an address of TCP end point.
  70  //
  71  // The network must be a TCP network name.
  72  //
  73  // If the host in the address parameter is not a literal IP address or
  74  // the port is not a literal port number, ResolveTCPAddr resolves the
  75  // address to an address of TCP end point.
  76  // Otherwise, it parses the address as a pair of literal IP address
  77  // and port number.
  78  // The address parameter can use a host name, but this is not
  79  // recommended, because it will return at most one of the host name's
  80  // IP addresses.
  81  //
  82  // See func [Dial] for a description of the network and address
  83  // parameters.
  84  func ResolveTCPAddr(network, address []byte) (*TCPAddr, error) {
  85  	switch network {
  86  	case "tcp", "tcp4", "tcp6":
  87  	case "": // a hint wildcard for Go 1.0 undocumented behavior
  88  		network = "tcp"
  89  	default:
  90  		return nil, UnknownNetworkError(network)
  91  	}
  92  	addrs, err := DefaultResolver.internetAddrList(context.Background(), network, address)
  93  	if err != nil {
  94  		return nil, err
  95  	}
  96  	return addrs.forResolve(network, address).(*TCPAddr), nil
  97  }
  98  
  99  // TCPAddrFromAddrPort returns addr as a [TCPAddr]. If addr.IsValid() is false,
 100  // then the returned TCPAddr will contain a nil IP field, indicating an
 101  // address family-agnostic unspecified address.
 102  func TCPAddrFromAddrPort(addr netip.AddrPort) *TCPAddr {
 103  	return &TCPAddr{
 104  		IP:   addr.Addr().AsSlice(),
 105  		Zone: addr.Addr().Zone(),
 106  		Port: int(addr.Port()),
 107  	}
 108  }
 109  
 110  // TCPConn is an implementation of the [Conn] interface for TCP network
 111  // connections.
 112  type TCPConn struct {
 113  	conn
 114  }
 115  
 116  // KeepAliveConfig contains TCP keep-alive options.
 117  //
 118  // If the Idle, Interval, or Count fields are zero, a default value is chosen.
 119  // If a field is negative, the corresponding socket-level option will be left unchanged.
 120  //
 121  // Note that prior to Windows 10 version 1709, neither setting Idle and Interval
 122  // separately nor changing Count (which is usually 10) is supported.
 123  // Therefore, it's recommended to set both Idle and Interval to non-negative values
 124  // in conjunction with a -1 for Count on those old Windows if you intend to customize
 125  // the TCP keep-alive settings.
 126  // By contrast, if only one of Idle and Interval is set to a non-negative value,
 127  // the other will be set to the system default value, and ultimately,
 128  // set both Idle and Interval to negative values if you want to leave them unchanged.
 129  //
 130  // Note that Solaris and its derivatives do not support setting Interval to a non-negative value
 131  // and Count to a negative value, or vice-versa.
 132  type KeepAliveConfig struct {
 133  	// If Enable is true, keep-alive probes are enabled.
 134  	Enable bool
 135  
 136  	// Idle is the time that the connection must be idle before
 137  	// the first keep-alive probe is sent.
 138  	// If zero, a default value of 15 seconds is used.
 139  	Idle time.Duration
 140  
 141  	// Interval is the time between keep-alive probes.
 142  	// If zero, a default value of 15 seconds is used.
 143  	Interval time.Duration
 144  
 145  	// Count is the maximum number of keep-alive probes that
 146  	// can go unanswered before dropping a connection.
 147  	// If zero, a default value of 9 is used.
 148  	Count int
 149  }
 150  
 151  // SyscallConn returns a raw network connection.
 152  // This implements the [syscall.Conn] interface.
 153  func (c *TCPConn) SyscallConn() (syscall.RawConn, error) {
 154  	if !c.ok() {
 155  		return nil, syscall.EINVAL
 156  	}
 157  	return newRawConn(c.fd), nil
 158  }
 159  
 160  // ReadFrom implements the [io.ReaderFrom] ReadFrom method.
 161  func (c *TCPConn) ReadFrom(r io.Reader) (int64, error) {
 162  	if !c.ok() {
 163  		return 0, syscall.EINVAL
 164  	}
 165  	n, err := c.readFrom(r)
 166  	if err != nil && err != io.EOF {
 167  		err = &OpError{Op: "readfrom", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
 168  	}
 169  	return n, err
 170  }
 171  
 172  // WriteTo implements the io.WriterTo WriteTo method.
 173  func (c *TCPConn) WriteTo(w io.Writer) (int64, error) {
 174  	if !c.ok() {
 175  		return 0, syscall.EINVAL
 176  	}
 177  	n, err := c.writeTo(w)
 178  	if err != nil && err != io.EOF {
 179  		err = &OpError{Op: "writeto", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
 180  	}
 181  	return n, err
 182  }
 183  
 184  // CloseRead shuts down the reading side of the TCP connection.
 185  // Most callers should just use Close.
 186  func (c *TCPConn) CloseRead() error {
 187  	if !c.ok() {
 188  		return syscall.EINVAL
 189  	}
 190  	if err := c.fd.closeRead(); err != nil {
 191  		return &OpError{Op: "close", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
 192  	}
 193  	return nil
 194  }
 195  
 196  // CloseWrite shuts down the writing side of the TCP connection.
 197  // Most callers should just use Close.
 198  func (c *TCPConn) CloseWrite() error {
 199  	if !c.ok() {
 200  		return syscall.EINVAL
 201  	}
 202  	if err := c.fd.closeWrite(); err != nil {
 203  		return &OpError{Op: "close", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
 204  	}
 205  	return nil
 206  }
 207  
 208  // SetLinger sets the behavior of Close on a connection which still
 209  // has data waiting to be sent or to be acknowledged.
 210  //
 211  // If sec < 0 (the default), the operating system finishes sending the
 212  // data in the background.
 213  //
 214  // If sec == 0, the operating system discards any unsent or
 215  // unacknowledged data.
 216  //
 217  // If sec > 0, the data is sent in the background as with sec < 0.
 218  // On some operating systems including Linux, this may cause Close to block
 219  // until all data has been sent or discarded.
 220  // On some operating systems after sec seconds have elapsed any remaining
 221  // unsent data may be discarded.
 222  func (c *TCPConn) SetLinger(sec int) error {
 223  	if !c.ok() {
 224  		return syscall.EINVAL
 225  	}
 226  	if err := setLinger(c.fd, sec); err != nil {
 227  		return &OpError{Op: "set", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
 228  	}
 229  	return nil
 230  }
 231  
 232  // SetKeepAlive sets whether the operating system should send
 233  // keep-alive messages on the connection.
 234  func (c *TCPConn) SetKeepAlive(keepalive bool) error {
 235  	if !c.ok() {
 236  		return syscall.EINVAL
 237  	}
 238  	if err := setKeepAlive(c.fd, keepalive); err != nil {
 239  		return &OpError{Op: "set", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
 240  	}
 241  	return nil
 242  }
 243  
 244  // SetKeepAlivePeriod sets the duration the connection needs to
 245  // remain idle before TCP starts sending keepalive probes.
 246  //
 247  // Note that calling this method on Windows prior to Windows 10 version 1709
 248  // will reset the KeepAliveInterval to the default system value, which is normally 1 second.
 249  func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error {
 250  	if !c.ok() {
 251  		return syscall.EINVAL
 252  	}
 253  	if err := setKeepAliveIdle(c.fd, d); err != nil {
 254  		return &OpError{Op: "set", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
 255  	}
 256  	return nil
 257  }
 258  
 259  // SetNoDelay controls whether the operating system should delay
 260  // packet transmission in hopes of sending fewer packets (Nagle's
 261  // algorithm).  The default is true (no delay), meaning that data is
 262  // sent as soon as possible after a Write.
 263  func (c *TCPConn) SetNoDelay(noDelay bool) error {
 264  	if !c.ok() {
 265  		return syscall.EINVAL
 266  	}
 267  	if err := setNoDelay(c.fd, noDelay); err != nil {
 268  		return &OpError{Op: "set", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
 269  	}
 270  	return nil
 271  }
 272  
 273  // MultipathTCP reports whether the ongoing connection is using MPTCP.
 274  //
 275  // If Multipath TCP is not supported by the host, by the other peer or
 276  // intentionally / accidentally filtered out by a device in between, a
 277  // fallback to TCP will be done. This method does its best to check if
 278  // MPTCP is still being used or not.
 279  //
 280  // On Linux, more conditions are verified on kernels >= v5.16, improving
 281  // the results.
 282  func (c *TCPConn) MultipathTCP() (bool, error) {
 283  	if !c.ok() {
 284  		return false, syscall.EINVAL
 285  	}
 286  	return isUsingMultipathTCP(c.fd), nil
 287  }
 288  
 289  func newTCPConn(fd *netFD, keepAliveIdle time.Duration, keepAliveCfg KeepAliveConfig, preKeepAliveHook func(*netFD), keepAliveHook func(KeepAliveConfig)) *TCPConn {
 290  	setNoDelay(fd, true)
 291  	if !keepAliveCfg.Enable && keepAliveIdle >= 0 {
 292  		keepAliveCfg = KeepAliveConfig{
 293  			Enable: true,
 294  			Idle:   keepAliveIdle,
 295  		}
 296  	}
 297  	c := &TCPConn{conn{fd}}
 298  	if keepAliveCfg.Enable {
 299  		if preKeepAliveHook != nil {
 300  			preKeepAliveHook(fd)
 301  		}
 302  		c.SetKeepAliveConfig(keepAliveCfg)
 303  		if keepAliveHook != nil {
 304  			keepAliveHook(keepAliveCfg)
 305  		}
 306  	}
 307  	return c
 308  }
 309  
 310  // DialTCP acts like [Dial] for TCP networks.
 311  //
 312  // The network must be a TCP network name; see func Dial for details.
 313  //
 314  // If laddr is nil, a local address is automatically chosen.
 315  // If the IP field of raddr is nil or an unspecified IP address, the
 316  // local system is assumed.
 317  func DialTCP(network []byte, laddr, raddr *TCPAddr) (*TCPConn, error) {
 318  	switch network {
 319  	case "tcp", "tcp4", "tcp6":
 320  	default:
 321  		return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: UnknownNetworkError(network)}
 322  	}
 323  	if raddr == nil {
 324  		return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: nil, Err: errMissingAddress}
 325  	}
 326  	sd := &sysDialer{network: network, address: raddr.String()}
 327  	var (
 328  		c   *TCPConn
 329  		err error
 330  	)
 331  	if sd.MultipathTCP() {
 332  		c, err = sd.dialMPTCP(context.Background(), laddr, raddr)
 333  	} else {
 334  		c, err = sd.dialTCP(context.Background(), laddr, raddr)
 335  	}
 336  	if err != nil {
 337  		return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: err}
 338  	}
 339  	return c, nil
 340  }
 341  
 342  // TCPListener is a TCP network listener. Clients should typically
 343  // use variables of type [Listener] instead of assuming TCP.
 344  type TCPListener struct {
 345  	fd *netFD
 346  	lc ListenConfig
 347  }
 348  
 349  // SyscallConn returns a raw network connection.
 350  // This implements the [syscall.Conn] interface.
 351  //
 352  // The returned RawConn only supports calling Control. Read and
 353  // Write return an error.
 354  func (l *TCPListener) SyscallConn() (syscall.RawConn, error) {
 355  	if !l.ok() {
 356  		return nil, syscall.EINVAL
 357  	}
 358  	return newRawListener(l.fd), nil
 359  }
 360  
 361  // AcceptTCP accepts the next incoming call and returns the new
 362  // connection.
 363  func (l *TCPListener) AcceptTCP() (*TCPConn, error) {
 364  	if !l.ok() {
 365  		return nil, syscall.EINVAL
 366  	}
 367  	c, err := l.accept()
 368  	if err != nil {
 369  		return nil, &OpError{Op: "accept", Net: l.fd.net, Source: nil, Addr: l.fd.laddr, Err: err}
 370  	}
 371  	return c, nil
 372  }
 373  
 374  // Accept implements the Accept method in the [Listener] interface; it
 375  // waits for the next call and returns a generic [Conn].
 376  func (l *TCPListener) Accept() (Conn, error) {
 377  	if !l.ok() {
 378  		return nil, syscall.EINVAL
 379  	}
 380  	c, err := l.accept()
 381  	if err != nil {
 382  		return nil, &OpError{Op: "accept", Net: l.fd.net, Source: nil, Addr: l.fd.laddr, Err: err}
 383  	}
 384  	return c, nil
 385  }
 386  
 387  // Close stops listening on the TCP address.
 388  // Already Accepted connections are not closed.
 389  func (l *TCPListener) Close() error {
 390  	if !l.ok() {
 391  		return syscall.EINVAL
 392  	}
 393  	if err := l.close(); err != nil {
 394  		return &OpError{Op: "close", Net: l.fd.net, Source: nil, Addr: l.fd.laddr, Err: err}
 395  	}
 396  	return nil
 397  }
 398  
 399  // Addr returns the listener's network address, a [*TCPAddr].
 400  // The Addr returned is shared by all invocations of Addr, so
 401  // do not modify it.
 402  func (l *TCPListener) Addr() Addr { return l.fd.laddr }
 403  
 404  // SetDeadline sets the deadline associated with the listener.
 405  // A zero time value disables the deadline.
 406  func (l *TCPListener) SetDeadline(t time.Time) error {
 407  	if !l.ok() {
 408  		return syscall.EINVAL
 409  	}
 410  	return l.fd.SetDeadline(t)
 411  }
 412  
 413  // File returns a copy of the underlying [os.File].
 414  // It is the caller's responsibility to close f when finished.
 415  // Closing l does not affect f, and closing f does not affect l.
 416  //
 417  // The returned os.File's file descriptor is different from the
 418  // connection's. Attempting to change properties of the original
 419  // using this duplicate may or may not have the desired effect.
 420  //
 421  // On Windows, the returned os.File's file descriptor is not
 422  // usable on other processes.
 423  func (l *TCPListener) File() (f *os.File, err error) {
 424  	if !l.ok() {
 425  		return nil, syscall.EINVAL
 426  	}
 427  	f, err = l.file()
 428  	if err != nil {
 429  		return nil, &OpError{Op: "file", Net: l.fd.net, Source: nil, Addr: l.fd.laddr, Err: err}
 430  	}
 431  	return
 432  }
 433  
 434  // ListenTCP acts like [Listen] for TCP networks.
 435  //
 436  // The network must be a TCP network name; see func Dial for details.
 437  //
 438  // If the IP field of laddr is nil or an unspecified IP address,
 439  // ListenTCP listens on all available unicast and anycast IP addresses
 440  // of the local system.
 441  // If the Port field of laddr is 0, a port number is automatically
 442  // chosen.
 443  func ListenTCP(network []byte, laddr *TCPAddr) (*TCPListener, error) {
 444  	switch network {
 445  	case "tcp", "tcp4", "tcp6":
 446  	default:
 447  		return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: laddr.opAddr(), Err: UnknownNetworkError(network)}
 448  	}
 449  	if laddr == nil {
 450  		laddr = &TCPAddr{}
 451  	}
 452  	sl := &sysListener{network: network, address: laddr.String()}
 453  	var (
 454  		ln  *TCPListener
 455  		err error
 456  	)
 457  	if sl.MultipathTCP() {
 458  		ln, err = sl.listenMPTCP(context.Background(), laddr)
 459  	} else {
 460  		ln, err = sl.listenTCP(context.Background(), laddr)
 461  	}
 462  	if err != nil {
 463  		return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: laddr.opAddr(), Err: err}
 464  	}
 465  	return ln, nil
 466  }
 467  
 468  // roundDurationUp rounds d to the next multiple of to.
 469  func roundDurationUp(d time.Duration, to time.Duration) time.Duration {
 470  	return (d + to - 1) / to
 471  }
 472