conn

package
v1.11.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2024 License: AGPL-3.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultUDPSocketBufferSize = 7 << 20

DefaultUDPSocketBufferSize is the default send and receive buffer size of UDP sockets.

We use the same value of 7 MiB as wireguard-go: https://github.com/WireGuard/wireguard-go/blob/12269c2761734b15625017d8565745096325392f/conn/controlfns.go#L13-L18

View Source
const SYS_RECVMMSG = unix.SYS_RECVMMSG
View Source
const SocketControlMessageBufferSize = socketControlMessageBufferSize

SocketControlMessageBufferSize specifies the buffer size for receiving socket control messages.

View Source
const TransparentSocketControlMessageBufferSize = unix.SizeofCmsghdr + (unix.SizeofSockaddrInet6+unix.SizeofPtr-1) & ^(unix.SizeofPtr-1)

TransparentSocketControlMessageBufferSize specifies the buffer size for receiving IPV6_RECVORIGDSTADDR socket control messages.

Variables

View Source
var (
	// DefaultTCPListenerSocketOptions is the default [ListenerSocketOptions] for TCP servers.
	DefaultTCPListenerSocketOptions = ListenerSocketOptions{
		TCPFastOpen: true,
	}

	// DefaultTCPListenConfig is the default [ListenConfig] for TCP listeners.
	DefaultTCPListenConfig = DefaultTCPListenerSocketOptions.ListenConfig()

	// DefaultUDPServerSocketOptions is the default [ListenerSocketOptions] for UDP servers.
	DefaultUDPServerSocketOptions = ListenerSocketOptions{
		SendBufferSize:    DefaultUDPSocketBufferSize,
		ReceiveBufferSize: DefaultUDPSocketBufferSize,
		PathMTUDiscovery:  true,
		ReceivePacketInfo: true,
	}

	// DefaultUDPServerListenConfig is the default [ListenConfig] for UDP servers.
	DefaultUDPServerListenConfig = DefaultUDPServerSocketOptions.ListenConfig()

	// DefaultUDPClientSocketOptions is the default [ListenerSocketOptions] for UDP clients.
	DefaultUDPClientSocketOptions = ListenerSocketOptions{
		SendBufferSize:    DefaultUDPSocketBufferSize,
		ReceiveBufferSize: DefaultUDPSocketBufferSize,
		PathMTUDiscovery:  true,
	}

	// DefaultUDPClientListenConfig is the default [ListenConfig] for UDP clients.
	DefaultUDPClientListenConfig = DefaultUDPClientSocketOptions.ListenConfig()
)
View Source
var (
	// DefaultTCPDialerSocketOptions is the default [DialerSocketOptions] for TCP clients.
	DefaultTCPDialerSocketOptions = DialerSocketOptions{
		TCPFastOpen:         true,
		TCPFastOpenFallback: true,
	}

	// DefaultTCPDialer is the default [Dialer] for TCP clients.
	DefaultTCPDialer = DefaultTCPDialerSocketOptions.Dialer()
)
View Source
var (
	ErrMessageTruncated        = errors.New("the packet is larger than the supplied buffer")
	ErrControlMessageTruncated = errors.New("the control message is larger than the supplied buffer")
)
View Source
var ALongTimeAgo = time.Unix(0, 0)

ALongTimeAgo is a non-zero time, far in the past, used for immediate deadlines.

Functions

func AddrPortMappedEqual added in v1.1.0

func AddrPortMappedEqual(l, r netip.AddrPort) bool

AddrPortMappedEqual returns whether the two addresses point to the same endpoint. An IPv4 address and an IPv4-mapped IPv6 address pointing to the same endpoint are considered equal. For example, 1.1.1.1:53 and [::ffff:1.1.1.1]:53 are considered equal.

func AddrPortToSockaddr

func AddrPortToSockaddr(addrPort netip.AddrPort) (name *byte, namelen uint32)

func AddrPortToSockaddrInet4

func AddrPortToSockaddrInet4(addrPort netip.AddrPort) unix.RawSockaddrInet4

func AddrPortToSockaddrInet6

func AddrPortToSockaddrInet6(addrPort netip.AddrPort) unix.RawSockaddrInet6

func AddrPortToSockaddrValue added in v1.3.0

func AddrPortToSockaddrValue(addrPort netip.AddrPort) (rsa6 unix.RawSockaddrInet6, namelen uint32)

func AddrPortUnmappedToSockaddr added in v1.4.0

func AddrPortUnmappedToSockaddr(addrPort netip.AddrPort) (name *byte, namelen uint32)

func NewRawUDPConn added in v1.7.0

func NewRawUDPConn(udpConn *net.UDPConn) (rawUDPConn, error)

NewRawUDPConn wraps a net.UDPConn in a [rawUDPConn] for batch I/O.

func ParseFlagsForError

func ParseFlagsForError(flags int) error

ParseFlagsForError parses the message flags returned by the ReadMsgUDPAddrPort method and returns an error if MSG_TRUNC is set, indicating that the returned packet was truncated.

The check is skipped on Windows, because an error (WSAEMSGSIZE) is also returned when MSG_PARTIAL is set.

func ParseOrigDstAddrCmsg added in v1.4.0

func ParseOrigDstAddrCmsg(cmsg []byte) (netip.AddrPort, error)

func ResolveIP added in v1.7.0

func ResolveIP(ctx context.Context, network, host string) (netip.Addr, error)

ResolveIP resolves a domain name string into an IP address.

The network must be one of "ip", "ip4" or "ip6". String representations of IP addresses are not supported.

This function always returns the first IP address returned by the resolver, because the resolver takes care of sorting the IP addresses by address family availability and preference.

func SockaddrInet4ToAddrPort added in v1.4.0

func SockaddrInet4ToAddrPort(sa *unix.RawSockaddrInet4) netip.AddrPort

func SockaddrInet6ToAddrPort added in v1.4.0

func SockaddrInet6ToAddrPort(sa *unix.RawSockaddrInet6) netip.AddrPort

func SockaddrToAddrPort

func SockaddrToAddrPort(name *byte, namelen uint32) (netip.AddrPort, error)

func SockaddrValueToAddrPort added in v1.3.0

func SockaddrValueToAddrPort(rsa6 unix.RawSockaddrInet6, namelen uint32) (netip.AddrPort, error)

Types

type Addr added in v1.1.0

type Addr struct {
	// contains filtered or unexported fields
}

Addr is the base address type used throughout the package.

An Addr is a port number combined with either an IP address or a domain name.

For space efficiency, the IP address and the domain string share the same space. The netip.Addr is stored in its original layout. The domain string's data pointer is stored in the ip.z field. Its length is stored at the beginning of the structure. This is essentially an unsafe "enum".

func AddrFromDomainPort added in v1.1.0

func AddrFromDomainPort(domain string, port uint16) (Addr, error)

AddrFromDomainPort returns an Addr from the provided domain name and port number.

func AddrFromHostPort added in v1.1.0

func AddrFromHostPort(host string, port uint16) (Addr, error)

AddrFromHostPort returns an Addr from the provided host string and port number. The host string may be a string representation of an IP address or a domain name.

func AddrFromIPPort added in v1.1.0

func AddrFromIPPort(addrPort netip.AddrPort) (addr Addr)

AddrFromIPPort returns an Addr from the provided netip.AddrPort.

func MustAddrFromDomainPort added in v1.1.0

func MustAddrFromDomainPort(domain string, port uint16) Addr

MustAddrFromDomainPort calls AddrFromDomainPort and panics on error.

func ParseAddr added in v1.1.0

func ParseAddr[T ~[]byte | ~string](s T) (Addr, error)

ParseAddr parses the provided string representation of an address and returns the parsed address or an error.

func (Addr) AppendTo added in v1.1.0

func (a Addr) AppendTo(b []byte) []byte

AppendTo appends the string representation of the address to the provided buffer.

If the address is zero value, nothing is appended.

func (Addr) Domain added in v1.1.0

func (a Addr) Domain() string

Domain returns the domain name.

If the address is an IP address or zero value, this method panics.

func (Addr) Equals added in v1.5.0

func (a Addr) Equals(b Addr) bool

Equals returns whether two addresses are the same.

func (Addr) Host added in v1.1.0

func (a Addr) Host() string

Host returns the string representation of the IP address or the domain name.

If the address is zero value, this method panics.

func (Addr) IP added in v1.1.0

func (a Addr) IP() netip.Addr

IP returns the IP address.

If the address is a domain name or zero value, this method panics.

func (Addr) IPPort added in v1.1.0

func (a Addr) IPPort() netip.AddrPort

IPPort returns a netip.AddrPort.

If the address is a domain name or zero value, this method panics.

func (Addr) IsDomain added in v1.5.0

func (a Addr) IsDomain() bool

IsDomain returns whether the address is a domain name.

func (Addr) IsIP added in v1.1.0

func (a Addr) IsIP() bool

IsIP returns whether the address is an IP address.

func (Addr) IsValid added in v1.5.0

func (a Addr) IsValid() bool

IsValid returns whether the address is an initialized address (not a zero value).

func (Addr) MarshalText added in v1.1.0

func (a Addr) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler MarshalText method.

func (Addr) Port added in v1.1.0

func (a Addr) Port() uint16

Port returns the port number.

func (Addr) ResolveIP added in v1.1.0

func (a Addr) ResolveIP(ctx context.Context, network string) (netip.Addr, error)

ResolveIP returns the IP address itself or the resolved IP address of the domain name.

The network is only used for domain name resolution and must be one of "ip", "ip4" or "ip6".

If the address is zero value, this method panics.

func (Addr) ResolveIPPort added in v1.1.0

func (a Addr) ResolveIPPort(ctx context.Context, network string) (netip.AddrPort, error)

ResolveIPPort returns the IP address itself or the resolved IP address of the domain name and the port number as a netip.AddrPort.

The network is only used for domain name resolution and must be one of "ip", "ip4" or "ip6".

If the address is zero value, this method panics.

func (Addr) String added in v1.1.0

func (a Addr) String() string

String returns the string representation of the address.

If the address is zero value, an empty string is returned.

func (*Addr) UnmarshalText added in v1.1.0

func (a *Addr) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler UnmarshalText method.

type Dialer added in v1.8.0

type Dialer tfo.Dialer

Dialer is tfo.Dialer but provides a subjectively nicer API.

func (*Dialer) DialTCP added in v1.8.0

func (d *Dialer) DialTCP(ctx context.Context, network, address string, b []byte) (*net.TCPConn, error)

DialTCP wraps tfo.Dialer.DialContext and returns a *net.TCPConn directly.

func (*Dialer) DialUDP added in v1.8.0

func (d *Dialer) DialUDP(ctx context.Context, network, address string) (*net.UDPConn, error)

DialUDP wraps net.Dialer.DialContext and returns a *net.UDPConn directly.

type DialerCache added in v1.7.0

type DialerCache map[DialerSocketOptions]Dialer

DialerCache is a map of DialerSocketOptions to Dialer.

func NewDialerCache added in v1.7.0

func NewDialerCache() DialerCache

NewDialerCache creates a new cache for Dialer with a few default entries.

func (DialerCache) Get added in v1.7.0

func (cache DialerCache) Get(dso DialerSocketOptions) (d Dialer)

Get returns a Dialer for the given DialerSocketOptions.

type DialerSocketOptions added in v1.7.0

type DialerSocketOptions struct {
	// Fwmark sets the dialer's fwmark on Linux, or user cookie on FreeBSD.
	//
	// Available on Linux and FreeBSD.
	Fwmark int

	// TrafficClass sets the traffic class of the dialer.
	//
	// Available on most platforms except Windows.
	TrafficClass int

	// TCPFastOpen enables TCP Fast Open on the dialer.
	//
	// Available on Linux, macOS, FreeBSD, and Windows.
	TCPFastOpen bool

	// TCPFastOpenFallback enables runtime detection of TCP Fast Open support on the dialer.
	//
	// When enabled, the dialer will connect without TFO if TFO is not available on the system.
	// When disabled, the dialer will abort if TFO cannot be enabled on the socket.
	//
	// Available on all platforms.
	TCPFastOpenFallback bool

	// MultipathTCP enables multipath TCP on the dialer.
	//
	// Unlike Go std, we make MPTCP strictly opt-in.
	// That is, if this field is false, MPTCP will be explicitly disabled.
	// This ensures that if Go std suddenly decides to enable MPTCP by default,
	// existing configurations won't encounter issues due to missing features in the kernel MPTCP stack,
	// such as TCP keepalive (as of Linux 6.5), and failed connect attempts won't always be retried once.
	//
	// Available on platforms supported by Go std's MPTCP implementation.
	MultipathTCP bool
}

DialerSocketOptions contains dialer-specific socket options.

func (DialerSocketOptions) Dialer added in v1.7.0

func (dso DialerSocketOptions) Dialer() Dialer

Dialer returns a Dialer with a control function that sets the socket options.

type ListenConfig added in v1.8.0

type ListenConfig struct {
	// contains filtered or unexported fields
}

ListenConfig wraps a tfo.ListenConfig and provides a subjectively nicer API.

func (*ListenConfig) ListenTCP added in v1.8.0

func (lc *ListenConfig) ListenTCP(ctx context.Context, network, address string) (tln *net.TCPListener, info SocketInfo, err error)

ListenTCP wraps tfo.ListenConfig.Listen and returns a *net.TCPListener directly.

func (*ListenConfig) ListenUDP added in v1.8.0

func (lc *ListenConfig) ListenUDP(ctx context.Context, network, address string) (uc *net.UDPConn, info SocketInfo, err error)

ListenUDP wraps net.ListenConfig.ListenPacket and returns a *net.UDPConn directly.

func (*ListenConfig) ListenUDPRawConn added in v1.8.0

func (lc *ListenConfig) ListenUDPRawConn(ctx context.Context, network, address string) (c rawUDPConn, info SocketInfo, err error)

ListenUDPRawConn is like [ListenUDP] but wraps the *net.UDPConn in a [rawUDPConn] for batch I/O.

type ListenConfigCache added in v1.7.0

type ListenConfigCache map[ListenerSocketOptions]ListenConfig

ListenConfigCache is a map of ListenerSocketOptions to ListenConfig.

func NewListenConfigCache added in v1.7.0

func NewListenConfigCache() ListenConfigCache

NewListenConfigCache creates a new cache for ListenConfig with a few default entries.

func (ListenConfigCache) Get added in v1.7.0

Get returns a ListenConfig for the given ListenerSocketOptions.

type ListenerSocketOptions added in v1.7.0

type ListenerSocketOptions struct {
	// SendBufferSize sets the send buffer size of the listener.
	//
	// Available on POSIX systems.
	SendBufferSize int

	// ReceiveBufferSize sets the receive buffer size of the listener.
	//
	// Available on POSIX systems.
	ReceiveBufferSize int

	// Fwmark sets the listener's fwmark on Linux, or user cookie on FreeBSD.
	//
	// Available on Linux and FreeBSD.
	Fwmark int

	// TrafficClass sets the traffic class of the listener.
	//
	// Available on most platforms except Windows.
	TrafficClass int

	// TCPFastOpenBacklog specifies the maximum number of pending TFO connections on Linux.
	// If the value is 0, Go std's listen(2) backlog is used.
	//
	// On other platforms, a non-negative value is ignored, as they do not have the option to set the TFO backlog.
	//
	// On all platforms, a negative value disables TFO.
	TCPFastOpenBacklog int

	// TCPDeferAcceptSecs sets TCP_DEFER_ACCEPT to the given number of seconds on the listener.
	//
	// Available on Linux.
	TCPDeferAcceptSecs int

	// TCPUserTimeoutMsecs sets TCP_USER_TIMEOUT to the given number of milliseconds on the listener.
	//
	// Available on Linux.
	TCPUserTimeoutMsecs int

	// ReusePort enables SO_REUSEPORT on the listener.
	//
	// Available on Linux and the BSDs.
	ReusePort bool

	// Transparent enables transparent proxy on the listener.
	//
	// Only available on Linux.
	Transparent bool

	// PathMTUDiscovery enables Path MTU Discovery on the listener.
	//
	// Available on Linux, macOS, FreeBSD, and Windows.
	PathMTUDiscovery bool

	// TCPFastOpen enables TCP Fast Open on the listener.
	//
	// Available on Linux, macOS, FreeBSD, and Windows.
	TCPFastOpen bool

	// TCPFastOpenFallback enables runtime detection of TCP Fast Open support on the listener.
	//
	// When enabled, the listener will start without TFO if TFO is not available on the system.
	// When disabled, the listener will abort if TFO cannot be enabled on the socket.
	//
	// Available on all platforms.
	TCPFastOpenFallback bool

	// MultipathTCP enables multipath TCP on the listener.
	//
	// Unlike Go std, we make MPTCP strictly opt-in.
	// That is, if this field is false, MPTCP will be explicitly disabled.
	// This ensures that if Go std suddenly decides to enable MPTCP by default,
	// existing configurations won't encounter issues due to missing features in the kernel MPTCP stack,
	// such as TCP keepalive (as of Linux 6.5), and failed connect attempts won't always be retried once.
	//
	// Available on platforms supported by Go std's MPTCP implementation.
	MultipathTCP bool

	// ProbeUDPGSOSupport enables best-effort probing of
	// UDP Generic Segmentation Offload (GSO) support on the listener.
	//
	// Available on Linux and Windows.
	ProbeUDPGSOSupport bool

	// UDPGenericReceiveOffload enables UDP Generic Receive Offload (GRO) on the listener.
	//
	// Available on Linux and Windows.
	UDPGenericReceiveOffload bool

	// ReceivePacketInfo enables the reception of packet information control messages on the listener.
	//
	// Available on Linux, macOS, and Windows.
	ReceivePacketInfo bool

	// ReceiveOriginalDestAddr enables the reception of original destination address control messages on the listener.
	//
	// Only available on Linux.
	ReceiveOriginalDestAddr bool
}

ListenerSocketOptions contains listener-specific socket options.

func (ListenerSocketOptions) ListenConfig added in v1.7.0

func (lso ListenerSocketOptions) ListenConfig() ListenConfig

ListenConfig returns a ListenConfig that sets the socket options.

type MmsgRConn added in v1.7.0

type MmsgRConn struct {
	// contains filtered or unexported fields
}

MmsgRConn wraps a net.UDPConn and provides the [ReadMsgs] method for reading multiple messages in a single recvmmsg(2) system call.

MmsgRConn is not safe for concurrent use. Use the [RConn] method to create a new MmsgRConn instance for each goroutine.

func (MmsgRConn) RConn added in v1.7.0

func (c MmsgRConn) RConn() *MmsgRConn

RConn returns a new MmsgRConn instance for batch reading.

func (*MmsgRConn) ReadMsgs added in v1.7.0

func (c *MmsgRConn) ReadMsgs(msgvec []Mmsghdr, flags int) (int, error)

ReadMsgs reads as many messages as possible into the given msgvec and returns the number of messages read or an error.

func (MmsgRConn) WConn added in v1.7.0

func (c MmsgRConn) WConn() *MmsgWConn

WConn returns a new MmsgWConn instance for batch writing.

type MmsgWConn added in v1.7.0

type MmsgWConn struct {
	// contains filtered or unexported fields
}

MmsgWConn wraps a net.UDPConn and provides the [WriteMsgs] method for writing multiple messages in a single sendmmsg(2) system call.

MmsgWConn is not safe for concurrent use. Use the [WConn] method to create a new MmsgWConn instance for each goroutine.

func (MmsgWConn) RConn added in v1.7.0

func (c MmsgWConn) RConn() *MmsgRConn

RConn returns a new MmsgRConn instance for batch reading.

func (MmsgWConn) WConn added in v1.7.0

func (c MmsgWConn) WConn() *MmsgWConn

WConn returns a new MmsgWConn instance for batch writing.

func (*MmsgWConn) WriteMsgs added in v1.7.0

func (c *MmsgWConn) WriteMsgs(msgvec []Mmsghdr, flags int) error

WriteMsgs writes all messages in the given msgvec and returns the last encountered error.

type Mmsghdr

type Mmsghdr struct {
	Msghdr unix.Msghdr
	Msglen uint32
}

type SocketControlMessage added in v1.11.2

type SocketControlMessage struct {
	// PktinfoAddr is the IP address of the network interface the packet was received from.
	PktinfoAddr netip.Addr

	// PktinfoIfindex is the index of the network interface the packet was received from.
	PktinfoIfindex uint32

	// SegmentSize is the UDP GRO/GSO segment size.
	SegmentSize uint32
}

SocketControlMessage contains information that can be parsed from or put into socket control messages.

func ParseSocketControlMessage added in v1.11.2

func ParseSocketControlMessage(cmsg []byte) (m SocketControlMessage, err error)

ParseSocketControlMessage parses a sequence of socket control messages and returns the parsed information.

func (SocketControlMessage) AppendTo added in v1.11.2

func (m SocketControlMessage) AppendTo(b []byte) []byte

AppendTo appends the socket control message to the buffer.

type SocketInfo added in v1.11.2

type SocketInfo struct {
	// MaxUDPGSOSegments is the maximum number of UDP GSO segments supported by the socket.
	//
	// If UDP GSO is not enabled on the socket, or the system does not support UDP GSO, the value is 1.
	//
	// The value is 0 if the socket is not a UDP socket.
	MaxUDPGSOSegments uint32

	// UDPGenericReceiveOffload indicates whether UDP GRO is enabled on the socket.
	UDPGenericReceiveOffload bool
}

SocketInfo contains information about a socket.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL