Documentation
¶
Overview ¶
Package netx provides reusable networking helpers for Go.
The root package holds portable connection helpers:
- Connection wrappers: TimeoutConn (idle timeout), FramedConn (length-prefixed messages as a stream or as datagrams), PrefixConn (replays bytes already read), RecordingConn (records reads), AddrOverrideConn, WrapConn and ObserveConn (traffic callbacks). The wrappers pass CloseWrite on, and InnermostConn and ConnAs unwrap them, and any connection with a NetConn method such as *tls.Conn. Peek and PeekFull read the first bytes of a connection and replay them.
- Relay copies between two connections in both directions until its context ends, optionally passing half-closes on, ending idle relays, and pacing and counting each direction through RelayFlow hooks; Copy copies one direction the same way. RelayEnd and ChainReader relay parts of connections, such as one exchange of a protocol, splicing an *io.LimitedReader over a connection. ConnGroup closes connections and relays together. DoWithContext bounds a blocking call on a connection with a context, and DoHandshake an exchange that closes the connection when it fails, as the handshakes of this module do.
- Addr is a destination as proxy requests name it, an IP address or a host name and a port, normalised so that policies see one form.
- Dialing: DialFirst returns the first of several dial attempts that connects, and RaceDialer races several dialers as a ContextDialer, or the addresses of a service with DialAny.
- Listeners: ChanListener accepts connections that the program delivers or dials in memory, NewSingleConnListener serves one connection, and ListenEphemeralUDP opens a UDP socket on a free port. Accept retries temporary Accept errors with a backoff. See udpflow.ListenUDPReusePort for UDP socket groups using SO_REUSEPORT.
- Error classification: IsTimeout, IsClosed, IsConnReset, IsConnRefused and the other Is* helpers, NetErrorKind and NetErrorDetails. They match platform errnos, including Winsock codes on Windows, before English error text.
Protocol and platform helpers live in subpackages:
- duplex joins a read half and a write half into one connection.
- forwarded interprets client metadata from trusted proxies.
- httphead parses HTTP/1.x heads and body framing.
- httpproxy serves HTTP forward proxies and CONNECT tunnels.
- httprewrite applies HTTP header and redirect rewrite rules.
- memnet provides in-process streams and datagrams for tests.
- proxydial dials through HTTP CONNECT, SOCKS5 and SOCKS4 proxies, with caller-supplied TLS for encrypted proxy connections.
- proxyproto builds, decodes and serves PROXY protocol headers.
- safedial dials and relays datagrams under a destination policy.
- socks5 implements SOCKS5 and SOCKS4 clients and servers.
- tlsconn runs bounded TLS handshakes and handles certificates.
- transparent accepts transparently redirected TCP and UDP flows.
- udpflow demultiplexes packet sockets into datagram connections.
- wsconn handles WebSocket handshakes, frames and stream adapters.
- wsconn/wshttp integrates WebSockets with net/http.
The module uses the standard library and github.com/djylb/timeshim, which itself uses only the standard library. The only packages that bring in crypto/tls are tlsconn directly and httprewrite and wsconn/wshttp through net/http.
Settings use the documented default for zero fields, omitted functional options and optional nil constructor arguments. Defaults for timeouts and limits are bounded unless documented otherwise. An explicit zero passed to an option or constructor follows that parameter's documented rule. A negative timeout disables it unless the setting says otherwise. Other negative values require a documented meaning. Servers and dialers expose settings as fields. Helpers use functional options for optional settings and ordinary arguments for required inputs.
Index ¶
- Constants
- Variables
- func Abort(c io.Closer, cause error)
- func Accept(ctx context.Context, l net.Listener) (net.Conn, error)
- func CloseBeneathTLS(c net.Conn)
- func ConnAs[T any](v any) (T, bool)
- func Copy(ctx context.Context, dst io.Writer, src io.Reader, f *RelayFlow) (int64, error)
- func DialFirst(ctx context.Context, stagger time.Duration, ...) (net.Conn, int, error)
- func DoHandshake(ctx context.Context, c net.Conn, fn func() error) error
- func DoWithContext(ctx context.Context, c net.Conn, fn func() error) error
- func EmbeddedIPv4(a netip.Addr) (netip.Addr, bool)
- func ErrnoName(err error) string
- func InnermostConn(v any) net.Conn
- func IsAcceptRetryable(err error) bool
- func IsAddrInUse(err error) bool
- func IsAddrNotAvailable(err error) bool
- func IsBrokenPipe(err error) bool
- func IsCanceled(err error) bool
- func IsClosed(err error) bool
- func IsConnAborted(err error) bool
- func IsConnRefused(err error) bool
- func IsConnReset(err error) bool
- func IsDNSError(err error) bool
- func IsDNSNotFound(err error) bool
- func IsGlobal(a netip.Addr) bool
- func IsHostUnreachable(err error) bool
- func IsMessageTooLarge(err error) bool
- func IsNetworkUnreachable(err error) bool
- func IsPermissionDenied(err error) bool
- func IsTimeout(err error) bool
- func IsWouldBlock(err error) bool
- func ListenEphemeralUDP(ctx context.Context, lc *net.ListenConfig) (*net.UDPConn, error)
- func ObserveConn(conn net.Conn, onRead, onWrite func(n int64) error) net.Conn
- func Peek(ctx context.Context, c net.Conn, n int) (net.Conn, []byte, error)
- func PeekFull(ctx context.Context, c net.Conn, n int) (net.Conn, []byte, error)
- func Relay(ctx context.Context, a, b io.ReadWriteCloser, opts ...RelayOption) (aToB, bToA int64, err error)
- func WrapConn(rwc io.ReadWriteCloser, parent net.Conn, opts ...WrapOption) net.Conn
- type Aborter
- type Addr
- type AddrOverrideConn
- func (c *AddrOverrideConn) Close() error
- func (c *AddrOverrideConn) CloseWrite() error
- func (c *AddrOverrideConn) LocalAddr() net.Addr
- func (c *AddrOverrideConn) NetConn() net.Conn
- func (c *AddrOverrideConn) NetxOwned() OwnedLayers
- func (c *AddrOverrideConn) Read(b []byte) (int, error)
- func (c *AddrOverrideConn) RemoteAddr() net.Addr
- func (c *AddrOverrideConn) SetDeadline(t time.Time) error
- func (c *AddrOverrideConn) SetReadDeadline(t time.Time) error
- func (c *AddrOverrideConn) SetWriteDeadline(t time.Time) error
- func (c *AddrOverrideConn) Write(b []byte) (int, error)
- func (c *AddrOverrideConn) WriteTo(w io.Writer) (int64, error)
- type ChainReader
- type ChanListener
- func (l *ChanListener) Accept() (net.Conn, error)
- func (l *ChanListener) Addr() net.Addr
- func (l *ChanListener) Close() error
- func (l *ChanListener) Deliver(ctx context.Context, c net.Conn) error
- func (l *ChanListener) Dial(ctx context.Context, remote net.Addr) (net.Conn, error)
- func (l *ChanListener) TryDeliver(c net.Conn) bool
- type ConnGroup
- type ContextDialer
- type ErrorKind
- type FramedConn
- func (fc *FramedConn) Close() error
- func (fc *FramedConn) CloseWrite() error
- func (fc *FramedConn) LocalAddr() net.Addr
- func (fc *FramedConn) NetConn() net.Conn
- func (fc *FramedConn) NetxOwned() OwnedLayers
- func (fc *FramedConn) Read(p []byte) (int, error)
- func (fc *FramedConn) ReadFrame() ([]byte, error)
- func (fc *FramedConn) RemoteAddr() net.Addr
- func (fc *FramedConn) SetDeadline(t time.Time) error
- func (fc *FramedConn) SetReadDeadline(t time.Time) error
- func (fc *FramedConn) SetWriteDeadline(t time.Time) error
- func (fc *FramedConn) Write(p []byte) (int, error)
- func (fc *FramedConn) WriteFrame(p []byte) error
- type FramedOption
- type NetErrorInfo
- type OwnedLayers
- type PrefixConn
- func (c *PrefixConn) Close() error
- func (c *PrefixConn) CloseWrite() error
- func (c *PrefixConn) LocalAddr() net.Addr
- func (c *PrefixConn) NetConn() net.Conn
- func (c *PrefixConn) NetxOwned() OwnedLayers
- func (c *PrefixConn) Read(b []byte) (int, error)
- func (c *PrefixConn) RemoteAddr() net.Addr
- func (c *PrefixConn) SetDeadline(t time.Time) error
- func (c *PrefixConn) SetReadDeadline(t time.Time) error
- func (c *PrefixConn) SetWriteDeadline(t time.Time) error
- func (c *PrefixConn) Write(b []byte) (int, error)
- func (c *PrefixConn) WriteTo(w io.Writer) (int64, error)
- type RaceDialer
- type ReadNotifier
- type RecordingConn
- func (c *RecordingConn) Buffered() []byte
- func (c *RecordingConn) Close() error
- func (c *RecordingConn) CloseWrite() error
- func (c *RecordingConn) Discard()
- func (c *RecordingConn) LocalAddr() net.Addr
- func (c *RecordingConn) NetConn() net.Conn
- func (c *RecordingConn) NetxOwned() OwnedLayers
- func (c *RecordingConn) Read(p []byte) (n int, err error)
- func (c *RecordingConn) Release() (net.Conn, []byte)
- func (c *RecordingConn) RemoteAddr() net.Addr
- func (c *RecordingConn) SetDeadline(t time.Time) error
- func (c *RecordingConn) SetReadDeadline(t time.Time) error
- func (c *RecordingConn) SetWriteDeadline(t time.Time) error
- func (c *RecordingConn) Stop()
- func (c *RecordingConn) Truncated() bool
- func (c *RecordingConn) Write(p []byte) (int, error)
- type RelayEnd
- type RelayError
- type RelayFlow
- type RelayOption
- type RelaySide
- type Scope
- type SingleConnListener
- type TimeoutConn
- func (c *TimeoutConn) Close() error
- func (c *TimeoutConn) CloseWrite() error
- func (c *TimeoutConn) IdleTimeout() time.Duration
- func (c *TimeoutConn) LocalAddr() net.Addr
- func (c *TimeoutConn) NetConn() net.Conn
- func (c *TimeoutConn) NetxOwned() OwnedLayers
- func (c *TimeoutConn) Read(b []byte) (int, error)
- func (c *TimeoutConn) RemoteAddr() net.Addr
- func (c *TimeoutConn) SetDeadline(t time.Time) error
- func (c *TimeoutConn) SetIdleTimeout(d time.Duration) error
- func (c *TimeoutConn) SetReadDeadline(t time.Time) error
- func (c *TimeoutConn) SetWriteDeadline(t time.Time) error
- func (c *TimeoutConn) Write(b []byte) (int, error)
- type WrapOption
Examples ¶
Constants ¶
const DefaultDialStagger = 300 * time.Millisecond
DefaultDialStagger is how long DialFirst waits for an attempt before it starts the next when stagger is 0.
const DefaultRecordingLimit = 64 * 1024
DefaultRecordingLimit is how many read bytes a RecordingConn records when NewRecordingConn is given no positive limit.
const MaxFramePayload = 65535
MaxFramePayload is the maximum payload size of one framed message.
const MaxNameLen = 255
MaxNameLen is the length of the longest host name an Addr holds, as DNS and SOCKS bound it.
Variables ¶
var ErrFrameDesync = errors.New("netx: framed stream desynchronized by a partial frame")
ErrFrameDesync is returned after a read or write failed in a way that lost frame bytes, such as the end of the stream inside a frame (see FramedConn). Frame boundaries in that direction are lost, so the error is sticky and the connection should be closed. Use errors.Is to detect it. The returned error also wraps the failure that caused it, so errors.Is and errors.As still see that cause (an EOF inside a frame as io.ErrUnexpectedEOF), except that a timeout cause is hidden and the error never reports a timeout.
var ErrFrameTooLarge = errors.New("netx: frame size exceeds MaxFramePayload")
ErrFrameTooLarge is returned by WriteFrame, and by Write in datagram mode, for a payload longer than MaxFramePayload.
var ErrGroupClosed = errors.New("netx: connection group closed")
ErrGroupClosed is returned by ConnGroup.Add on a group that Close closed.
var ErrInvalidAddr = errors.New("netx: invalid address")
ErrInvalidAddr reports an address that cannot be parsed or encoded.
var ErrNoDialAttempts = errors.New("netx: nothing to dial")
ErrNoDialAttempts is returned by DialFirst without attempts and by RaceDialer.DialAny without addresses.
var ErrRelayGroupClosed = errors.New("netx: relay closed by its group")
ErrRelayGroupClosed is returned by a Relay that a ConnGroup closed; see WithRelayGroup.
var ErrRelayIdle = errors.New("netx: relay idle")
ErrRelayIdle is returned by a Relay that WithRelayIdleTimeout ended.
var ErrWouldBlock error = wouldBlockError{}
ErrWouldBlock is returned by ReadNotifier.TryRead when the source holds nothing to read yet and has neither ended nor failed. It also ends an io.ReaderFrom that Relay feeds only while its source has data; see Relay. Its WouldBlock method reports true, so IsWouldBlock recognizes it; a source may return an error of its own instead.
Functions ¶
func Abort ¶
Abort ends c abnormally, so that its peer reads an error, not an end of data: an Aborter, c itself or the first one beneath its wrappers, as reached through owned connections, is aborted with cause; otherwise a *net.TCPConn beneath c gets SO_LINGER 0, so that closing it sends RST instead of FIN. Then c is closed, unless it is an Aborter itself. A connection with neither is just closed, as a *net.UnixConn or a datagram connection, whose peers cannot tell the two apart.
func Accept ¶
Accept waits for the next connection of l. It calls l.Accept again after the errors for which IsAcceptRetryable reports true: at once after the first, as such an error concerns one connection, and then, while they persist, after a delay that doubles from 1ms up to 1s, so that a server out of file descriptors does not spin. It returns the first other error, such as that of a closed listener, or ctx's error when ctx ends while it waits to retry. ctx does not end a blocked l.Accept; close l for that.
func CloseBeneathTLS ¶
CloseBeneathTLS closes the connection beneath c when c is a TLS connection. Call it before closing c after an exchange over c timed out or was canceled, as DoHandshake does: a TLS connection whose write was cut short would still send close_notify on Close, under a record number that the peer cannot authenticate, so the peer would see a TLS failure instead of the end of the connection. With the connection beneath closed, c's Close sends nothing.
A TLS connection is one with the NetConn and HandshakeContext methods of *tls.Conn, so that this package does not link crypto/tls and the connections of other TLS implementations can declare their transport with NetxOwned. Only the transport owned by c is closed.
func ConnAs ¶
ConnAs returns the first connection of type T in the chain beneath v, v included, as errors.As does for errors: through the wrappers of this package and NetConn methods, such as to find the *tls.Conn or *TimeoutConn beneath other wrappers.
func Copy ¶
Copy copies src to dst until src's EOF or an error, as one direction of a Relay does, with the same splicing, waiting without a buffer and handling of datagrams, paced and counted by f, which may be nil for neither. It closes neither end and returns the bytes copied and nil at EOF, or the error that stopped it; f.End is called before it returns.
ctx ends a blocked f.Wait, and, since Copy does not close the ends, once ctx is done Copy sets an expired read deadline on src and an expired write deadline on dst, those that have SetReadDeadline and SetWriteDeadline, to interrupt a blocked read or write, and returns context.Cause(ctx); the deadlines stay set for the caller to reset. A source or destination without deadlines must be closed to end a Copy blocked on it.
func DialFirst ¶
func DialFirst(ctx context.Context, stagger time.Duration, attempts ...func(context.Context) (net.Conn, error)) (net.Conn, int, error)
DialFirst runs attempts, which may dial in different ways, such as directly and through a relay, and returns the first connection made and the index of the attempt that made it. It starts them in order, starting the next while earlier ones go on whenever one has not connected within stagger, or at once when one fails; a stagger of 0 means DefaultDialStagger, and a negative one starts the next only when one fails, as a negative net.Dialer.FallbackDelay does. The other attempts are cancelled, and connections they still make are closed.
When none connects, it returns -1 and the errors of every attempt, joined, or ctx's error when ctx ended the dial. An attempt that returns a connection with an error fails, and its connection is closed.
func DoHandshake ¶
DoHandshake runs fn, an exchange on c that c is no use without, such as a proxy handshake, bounded by ctx as with DoWithContext, and closes c when it fails: c belongs to the caller after a success and is closed after a failure, the rule that every handshake of this module follows. When ctx ended the exchange or its I/O timed out, a write may have been cut short, so the connection beneath a TLS c is closed first, as by CloseBeneathTLS, and closing c sends no close_notify that the peer cannot authenticate.
func DoWithContext ¶
DoWithContext runs fn, which does I/O on c, such as reading a request, bounded by ctx: ctx's deadline becomes c's deadline, and once ctx is done c's deadline is set in the past to interrupt the I/O. For a cancelable ctx, a connection that rejects a deadline returns an error before fn starts. When fn returns, c's deadline is cleared. It returns ctx's error when ctx ended fn, also context.DeadlineExceeded when c's deadline, which is ctx's, expired just before ctx reported it, and otherwise fn's error.
As an I/O helper it leaves c open on failure, as Peek does, since a failure need not end the connection, such as a sniffing read that times out before a client that waits for the server to speak first. For an exchange that c is no use without, such as a protocol handshake, use DoHandshake, which closes c on failure as the handshakes of this module do.
func EmbeddedIPv4 ¶
EmbeddedIPv4 returns the IPv4 address that a carries in its IPv6 form, the address that a translator or relay on the path delivers to: an IPv4-mapped address (::ffff:a.b.c.d), the NAT64 well-known prefix 64:ff9b::/96 (RFC 6052), the NAT64 local-use prefix 64:ff9b:1::/48 in the RFC 6052 /48 layout (RFC 8215), 6to4 2002::/16 (RFC 3056) and the deprecated IPv4-compatible form ::a.b.c.d (RFC 4291), apart from :: and ::1, which are IPv6's own. It reports false for an IPv4 address and for an IPv6 address of any other form; a Teredo address carries two IPv4 addresses, and ScopeOf judges both. The zone is ignored.
A policy that judges addresses by range should judge an address that embeds IPv4 also by the embedded address, so that the same host cannot be reached under another spelling.
func ErrnoName ¶
ErrnoName returns the POSIX name of the platform errno in err's chain for the errnos that the classifiers know, such as ECONNRESET also for WSAECONNRESET, or "".
func InnermostConn ¶
InnermostConn returns the innermost connection beneath v: it follows the wrappers of this package and the NetConn() net.Conn methods of others, such as *tls.Conn's, which return the connection one layer down. It returns v itself when v wraps nothing, and nil for a nil connection, also a nil pointer such as a nil *net.TCPConn, and for a value that is not a connection. The connection is borrowed: v's owner still closes it.
func IsAcceptRetryable ¶
IsAcceptRetryable reports whether err, returned by a listener's Accept, is worth calling Accept again for, as net/http decides: a timeout, or an error that reports itself temporary, such as running out of file descriptors (EMFILE, ENFILE) or a connection that the client aborted before it was accepted (ECONNABORTED). An error of a closed listener is not.
func IsAddrInUse ¶
IsAddrInUse reports whether err looks like an address already in use, as when a listener's port is taken.
func IsAddrNotAvailable ¶
IsAddrNotAvailable reports whether err looks like an address that is not available on this host, as when binding to an address of another host.
func IsBrokenPipe ¶
IsBrokenPipe reports whether err looks like a broken pipe.
func IsCanceled ¶
IsCanceled reports whether err comes from a canceled context or operation: context.Canceled, which a canceled dial or lookup of package net matches, or the "operation was canceled" text that some wrappers pass on without the error value.
func IsClosed ¶
IsClosed reports whether err comes from using a closed connection or listener: net.ErrClosed, io.ErrClosedPipe, or the "use of closed network connection" text that some wrappers pass on without the error value.
func IsConnAborted ¶
IsConnAborted reports whether err looks like an aborted connection.
func IsConnRefused ¶
IsConnRefused reports whether err looks like a refused connection attempt.
func IsConnReset ¶
IsConnReset reports whether err looks like a connection reset.
func IsDNSError ¶
IsDNSError reports whether err is a failed name lookup: a *net.DNSError in the chain.
func IsDNSNotFound ¶
IsDNSNotFound reports whether err is a lookup of a name or record that does not exist, as opposed to a failure to ask, such as a timeout.
func IsGlobal ¶
IsGlobal reports whether a is globally reachable unicast, ScopeOf(a) == ScopeGlobal: not private, shared, loopback, link-local, multicast, documentation, benchmarking, reserved or unspecified.
func IsHostUnreachable ¶
IsHostUnreachable reports whether err looks like an unreachable host. A failed lookup is KindDNS for NetErrorKind, whatever its cause; IsDNSError tells it apart.
func IsMessageTooLarge ¶
IsMessageTooLarge reports whether err looks like a datagram too large to send or receive whole.
func IsNetworkUnreachable ¶
IsNetworkUnreachable reports whether err looks like an unreachable network.
func IsPermissionDenied ¶
IsPermissionDenied reports whether err looks like a permission failure (EACCES or EPERM), such as a connect blocked by a local firewall rule.
func IsTimeout ¶
IsTimeout reports whether err is a timeout. It matches ETIMEDOUT (WSAETIMEDOUT on Windows) anywhere in the chain first, then the first net.Error's Timeout method, and only then English timeout messages.
func IsWouldBlock ¶
IsWouldBlock reports whether err, or an error it wraps, has a method WouldBlock() bool that reports true, as ErrWouldBlock does: the error says that a read found nothing yet, not that it failed. A source can so signal it without depending on this package.
func ListenEphemeralUDP ¶
ListenEphemeralUDP opens a UDP socket on a free port of every local address, with lc, nil meaning a zero net.ListenConfig, so that its Control can set socket options, for IPv4 and IPv6 where the system has both, as net.ListenUDP("udp", nil) does. On macOS and iOS, that call can take a port that another socket holds on one IPv4 address, such as 127.0.0.1, which then receives the datagrams sent to that address and port; this function takes a port free for IPv4 instead, and falls back to that call when it finds none, as when the IPv4 ports run out.
func ObserveConn ¶
ObserveConn wraps conn and reports the bytes of each successful read to onRead and of each write to onWrite, either of which may be nil. An error from one is joined to the error of that Read or Write, so that it can end the connection's use, such as when an allowance runs out. With neither, conn is returned as it is.
To count and pace a Relay, use WithRelayFlows instead: a Relay cannot splice through, or wait for data without a buffer on, a connection that ObserveConn wraps.
func Peek ¶
Peek reads the first bytes of c, at most n, as for sniffing the protocol of a connection before it is handed on, and returns them with a connection that replays them before the rest of c. It returns after the first read that brings data, so a peer whose first message is shorter than n does not stall it; use PeekFull for exactly n bytes. ctx bounds the wait as DoWithContext does: its deadline becomes c's, and c's deadline is cleared again when Peek returns. The error is that of the read, or ctx's; c is left open and the returned connection is valid also then, so that a read that times out before a peer that waits for the server to speak first can still hand the connection on.
On a connection whose Reads return one datagram each, such as one of a PacketListener, Peek reads the first datagram whole, returns up to n of its bytes, and the returned connection replays the whole datagram, so that sniffing does not cut it short.
Example ¶
Hand a connection on after sniffing its first bytes.
package main
import (
"context"
"fmt"
"io"
"net"
"github.com/djylb/netx"
)
func main() {
client, server := net.Pipe()
go func() {
_, _ = client.Write([]byte("GET / HTTP/1.1\r\n"))
_ = client.Close()
}()
c, head, _ := netx.PeekFull(context.Background(), server, 4)
fmt.Printf("%q\n", head)
all, _ := io.ReadAll(c) // the next reader sees the whole request
fmt.Printf("%q\n", all)
}
Output: "GET " "GET / HTTP/1.1\r\n"
func PeekFull ¶
PeekFull is Peek reading exactly n bytes, or fewer if a read fails first. On a datagram connection it reads one datagram, as Peek does.
func Relay ¶
func Relay(ctx context.Context, a, b io.ReadWriteCloser, opts ...RelayOption) (aToB, bToA int64, err error)
Relay copies data between a and b in both directions and closes both when it returns. By default it stops as soon as either direction stops, at EOF or on an error, ending both ends to end the other direction; see WithRelayHalfClose.
Only a normal end, EOF, is passed on as an end of data: Relay then closes both ends, or with WithRelayHalfClose shuts down the writing side of the other end. Any other stop, an error in either direction, such as a reset by a peer or an error of a RelayFlow hook, the end of ctx, the idle timeout or a ConnGroup, aborts both ends with Abort instead, a *net.TCPConn with RST and an Aborter with its Abort, so that neither peer takes a cut transfer for a complete one.
The end of ctx stops the relay too, aborting both ends, and Relay then returns context.Cause(ctx), unless it had stopped already: cancel a context that many relays share, with a cause, to end them all, for example when an allowance runs out or a service is disabled; relays blocked in a read end too, which an error from RelayFlow.Done cannot do. A ctx that is done already passes no byte.
It returns the bytes copied from a to b and from b to a, and the error that stopped the relay, or nil if it stopped at EOF. The failure of a direction is a *RelayError, which tells which end's data was being copied, so that a caller can close each end with a cause of its own; the end of ctx, the idle timeout and a ConnGroup stop it with their own errors, as described above. Errors caused by Relay closing the connections are not reported.
On Linux and Android, a direction between a *net.TCPConn and another *net.TCPConn or a *net.UnixConn is left to the kernel with splice, through a pipe that it holds only while data moves. Relay looks through PrefixConns, AddrOverrideConns, TimeoutConns, whose idle deadlines it then refreshes itself, and the connections of ConnGroup.Track and NewSingleConnListener, for splice and its other fast paths, but not through other wrappers. Otherwise a direction is copied with the reading end's WriteTo or else the writing end's ReadFrom, as io.Copy would, except those of *net.TCPConn, whose data goes through a pooled 32 KiB buffer instead. A stream read straight from a socket takes that buffer only once the socket is readable, on Unix systems, so that an idle relay holds none, and is fed to the writing end's ReadFrom only while it has data: once the socket would block, ReadFrom's read fails, ReadFrom returns, and it is called again when the socket is readable, so that what it takes for a read is not held while the direction is idle. ReadFrom must return the read error, as io.ReaderFrom does, and stay usable after it.
A direction from a ReadNotifier, such as a stream of a multiplexed connection, also beneath the wrappers above, is copied without a goroutine of its own: each notification starts a task that copies through the pooled buffer until TryRead would block, so that an idle relay between such a stream and a TCP connection keeps only the goroutine that called Relay, waiting for the TCP side. The rest of the prefix of a PrefixConn above the stream is readable at once: it is copied without waiting for the stream. A task blocked on a write holds the stream back, as a blocked copy would.
A source that returns one datagram per Read, such as a *net.UDPConn, a udpflow.PacketListener connection, a FramedConn with WithFramedDatagrams, or a connection of another package whose LocalAddr is on a datagram network (udp, ip, unixgram), has each datagram written whole with one Write, empty ones included. A PacketListener connection hands its queued datagrams over and a FramedConn reads each frame into a buffer that fits it, so that an idle relay holds no buffer and each datagram is copied once, and RelayFlow.Done may see more than Wait's n for one; other sources get a 64 KiB buffer, the largest UDP datagram.
Example ¶
Forward a client to an echo backend.
package main
import (
"context"
"fmt"
"io"
"net"
"github.com/djylb/netx"
)
func main() {
client, front := net.Pipe()
back, backend := net.Pipe()
go func() { _, _ = io.Copy(backend, backend) }()
done := make(chan struct{})
go func() {
up, down, err := netx.Relay(context.Background(), front, back)
fmt.Println(up, down, err)
close(done)
}()
_, _ = client.Write([]byte("ping"))
buf := make([]byte, 4)
_, _ = io.ReadFull(client, buf)
fmt.Println(string(buf))
_ = client.Close()
<-done
}
Output: ping 4 4 <nil>
func WrapConn ¶
func WrapConn(rwc io.ReadWriteCloser, parent net.Conn, opts ...WrapOption) net.Conn
WrapConn exposes rwc as a net.Conn using parent for addresses and deadlines. A nil parent is rwc itself when it is a net.Conn, so that its own wrappers keep their addresses and deadlines, and otherwise the connection beneath it. Closing the returned connection closes rwc. Use WithWrapParentClose to also close parent. When rwc is a ReadNotifier, so is the returned connection.
Types ¶
type Aborter ¶
type Aborter interface {
Abort(cause error)
}
Aborter is a connection that can end abnormally, so that its peer sees a cut instead of an end of data: a stream of a multiplexed connection resets itself, a WebSocket connection drops its transport without a closing handshake. Abort ends both directions at once, ends the reads and writes that block on the connection and releases it as Close does; a Close afterwards must be harmless. cause tells why, for the connection's own reporting, and may be nil.
Abort and Relay use it, also beneath the wrappers of this package, TLS, and wrappers declaring OwnedLayers; a *net.TCPConn needs none, as it is reset with SO_LINGER 0.
type Addr ¶
Addr is a destination as proxy requests name it: an IP address or a host name, and a port. When IP is valid it is used and Name is ignored. The zero Addr stands for no address and prints as "0.0.0.0:0".
The constructors of this module put every IP address in IP, in one form: an IPv4-mapped IPv6 address as IPv4, without a zone, also when it comes as a name that is an IP literal, such as "127.0.0.1" or "::1", or one with a trailing dot, such as "127.0.0.1.", which some resolvers connect to as that address; and names in lower case, with a trailing dot kept. Names are not resolved. A policy on IP addresses that sees an Addr, such as a proxy server's Allow hook, must therefore also check the addresses that names resolve to, where they are dialed, for example with a net.Dialer Control function, since some resolvers turn legacy forms such as "127.1" or "0x7f.0.0.1" into addresses. The unspecified addresses 0.0.0.0 and :: reach the local host on many systems.
func AddrFromAddrPort ¶
AddrFromAddrPort returns the Addr of ap, normalised as described at Addr.
Example ¶
Convert the source of a datagram, as net.UDPConn.ReadFromUDPAddrPort returns it, to an Addr; an IPv4 peer of a dual-stack socket comes as an IPv4-mapped IPv6 address, and a link-local one with a zone.
package main
import (
"fmt"
"net/netip"
"github.com/djylb/netx"
)
func main() {
fmt.Println(netx.AddrFromAddrPort(netip.MustParseAddrPort("[::ffff:192.0.2.1]:53")))
fmt.Println(netx.AddrFromAddrPort(netip.MustParseAddrPort("[fe80::1%eth0]:5353")))
}
Output: 192.0.2.1:53 [fe80::1]:5353
func AddrFromNetAddr ¶
AddrFromNetAddr converts a *net.TCPAddr, a *net.UDPAddr, an Addr, or another net.Addr whose String is "host:port". It returns the zero Addr for nil, a nil pointer or an address it cannot split.
func HostAddr ¶
HostAddr returns the Addr of host, an IP literal or a name, and port, normalised as described at Addr. It does not check that a name is valid.
func ParseAddr ¶
ParseAddr parses "host:port", where host is an IP literal, IPv6 in brackets, or a name of at most MaxNameLen bytes, normalised as described at Addr.
type AddrOverrideConn ¶
type AddrOverrideConn struct {
// contains filtered or unexported fields
}
AddrOverrideConn is a net.Conn that reports overridden local and remote addresses. A nil override falls back to the wrapped connection's address.
func NewAddrOverrideConn ¶
func NewAddrOverrideConn(c net.Conn, local, remote net.Addr) *AddrOverrideConn
NewAddrOverrideConn wraps c and overrides its local or remote address, in the order of LocalAddr and RemoteAddr; a nil address keeps c's own.
func (*AddrOverrideConn) Close ¶
func (c *AddrOverrideConn) Close() error
Close implements net.Conn.
func (*AddrOverrideConn) CloseWrite ¶
func (c *AddrOverrideConn) CloseWrite() error
CloseWrite shuts down the writing side of the wrapped connection; see TimeoutConn.CloseWrite.
func (*AddrOverrideConn) LocalAddr ¶
func (c *AddrOverrideConn) LocalAddr() net.Addr
LocalAddr implements net.Conn.
func (*AddrOverrideConn) NetConn ¶
func (c *AddrOverrideConn) NetConn() net.Conn
NetConn returns the connection that c wraps, as *tls.Conn's NetConn does; see InnermostConn and ConnAs.
func (*AddrOverrideConn) NetxOwned ¶
func (c *AddrOverrideConn) NetxOwned() OwnedLayers
NetxOwned describes the children closed with this layer.
func (*AddrOverrideConn) RemoteAddr ¶
func (c *AddrOverrideConn) RemoteAddr() net.Addr
RemoteAddr implements net.Conn.
func (*AddrOverrideConn) SetDeadline ¶
func (c *AddrOverrideConn) SetDeadline(t time.Time) error
SetDeadline implements net.Conn.
func (*AddrOverrideConn) SetReadDeadline ¶
func (c *AddrOverrideConn) SetReadDeadline(t time.Time) error
SetReadDeadline implements net.Conn.
func (*AddrOverrideConn) SetWriteDeadline ¶
func (c *AddrOverrideConn) SetWriteDeadline(t time.Time) error
SetWriteDeadline implements net.Conn.
type ChainReader ¶
type ChainReader struct {
Next func() (io.Reader, error)
// contains filtered or unexported fields
}
ChainReader reads the parts that Next returns one after another, as io.MultiReader does, but lazily: Next is called for the first part, and for the next one each time a part reaches EOF, until it returns a nil part, so that what follows can depend on what came before, as an HTTP body depends on its head. Relay and Copy copy each part as they would copy it as a source of its own, so that a part that is a connection, or an *io.LimitedReader over one, is spliced where the connection would be. An error of Next ends the reading with it. A ChainReader is not safe for concurrent use.
type ChanListener ¶
type ChanListener struct {
// contains filtered or unexported fields
}
ChanListener is a net.Listener fed by the program instead of a socket. Deliver hands it a connection accepted elsewhere, and Dial connects to it through an in-memory pipe. Accept returns the connections in order. All methods are safe for concurrent use. The zero value is ready to use, as a ChanListener of NewChanListener(nil, 0).
Example ¶
Serve HTTP on connections that never touch a socket.
package main
import (
"context"
"fmt"
"io"
"log"
"net"
"net/http"
"github.com/djylb/netx"
)
func main() {
l := netx.NewChanListener(nil, 16)
srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprint(w, "hello from ", r.RemoteAddr)
})}
go func() { _ = srv.Serve(l) }()
defer func() { _ = srv.Close() }()
client := &http.Client{Transport: &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return l.Dial(ctx, &net.TCPAddr{IP: net.IPv4(192, 0, 2, 1), Port: 4000})
},
}}
resp, err := client.Get("http://in-memory/")
if err != nil {
log.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
Output: hello from 192.0.2.1:4000
func NewChanListener ¶
func NewChanListener(addr net.Addr, queue int) *ChanListener
NewChanListener returns a ChanListener that reports addr from Addr and holds up to queue connections that Accept has not taken yet. A nil addr is reported as "pipe". With a non-positive queue, Deliver and Dial wait for Accept.
func (*ChanListener) Accept ¶
func (l *ChanListener) Accept() (net.Conn, error)
Accept waits for the next queued connection. It returns net.ErrClosed once l is closed.
func (*ChanListener) Addr ¶
func (l *ChanListener) Addr() net.Addr
Addr returns the address given to NewChanListener, or "pipe".
func (*ChanListener) Close ¶
func (l *ChanListener) Close() error
Close stops l and closes the connections still queued. Blocked Accept, Deliver and Dial calls return net.ErrClosed. A nil listener returns net.ErrClosed. Concurrent and reentrant Close calls can return before the queue drains.
func (*ChanListener) Deliver ¶
Deliver queues c for Accept, waiting for queue space until ctx is done or l is closed. On success l owns c: Accept returns it, or Close closes it. On failure it returns ctx.Err() or net.ErrClosed and c stays the caller's, to close or to hand elsewhere.
func (*ChanListener) Dial ¶
Dial connects to l through a synchronous in-memory net.Pipe and returns the client end. The server end is queued as by Deliver. It reports remote as its RemoteAddr and l.Addr() as its LocalAddr, and the client end reports the reverse; a nil remote is reported as "pipe".
func (*ChanListener) TryDeliver ¶
func (l *ChanListener) TryDeliver(c net.Conn) bool
TryDeliver queues c for Accept if the queue has room and l is open, and reports whether it did; l then owns c, as after Deliver. Otherwise c stays the caller's.
type ConnGroup ¶
type ConnGroup struct {
// contains filtered or unexported fields
}
ConnGroup tracks connections, or anything else that closes, so that they can be closed together, such as every connection of one user when its allowance runs out or the service is disabled. A connection may be in several groups, such as those of its user, client and service, and a group may be in another: closing the members of the outer group closes those of the inner one, and closing the outer group closes the inner one. A Relay joins with WithRelayGroup, which also ends a RelayFlow.Wait that blocks. Its methods are safe for concurrent use. The zero value is an empty, open group.
Example ¶
Close every connection of a group at once.
package main
import (
"fmt"
"net"
"github.com/djylb/netx"
)
func main() {
var user netx.ConnGroup
a, b := net.Pipe()
remove, _ := user.Add(a)
defer remove()
fmt.Println(user.Len())
_ = user.CloseMembers(nil)
_, err := b.Read(make([]byte, 1))
fmt.Println(user.Len(), err)
}
Output: 1 0 EOF
func (*ConnGroup) Add ¶
Add adds c and returns a function that removes it again, which the owner of c calls once it is done with c, closed or not; calling it more than once is harmless. On a group that Close closed, Add returns ErrGroupClosed and leaves c to its owner. Add rejects nil members, including typed nils.
func (*ConnGroup) Close ¶
Close closes the members of the group, as CloseMembers does but closing groups among them for good too, and makes Add refuse new members.
func (*ConnGroup) CloseMembers ¶
CloseMembers closes the members of the group and removes them; the group takes new ones afterwards. Relays among them return cause too, if it is not nil, and groups among them close their own members the same way and stay open. It returns the errors of the members' Close methods, joined. The members are closed without the group's lock, so a Close that blocks, as a TLS connection's may, holds up neither Add nor removes.
func (*ConnGroup) Len ¶
Len returns the number of members in the group: connections, groups, and relays that joined with WithRelayGroup.
type ContextDialer ¶
type ContextDialer = netutil.ContextDialer
ContextDialer dials connections with a DialContext(ctx, network, address) (net.Conn, error) method. *net.Dialer implements it, as do the dialers of the proxydial, socks5 and tlsconn packages. It is the same type as tlsconn.ContextDialer.
type ErrorKind ¶
type ErrorKind string
ErrorKind is a stable category of a network error, for metrics and logs; see NetErrorKind.
const ( KindNone ErrorKind = "none" KindCanceled ErrorKind = "canceled" KindDNS ErrorKind = "dns" KindConnReset ErrorKind = "conn_reset" KindConnAborted ErrorKind = "conn_aborted" KindBrokenPipe ErrorKind = "broken_pipe" KindConnRefused ErrorKind = "conn_refused" KindHostUnreachable ErrorKind = "host_unreachable" KindNetworkUnreachable ErrorKind = "network_unreachable" KindPermissionDenied ErrorKind = "permission_denied" KindAddrInUse ErrorKind = "addr_in_use" KindAddrNotAvailable ErrorKind = "addr_not_available" KindMessageTooLarge ErrorKind = "message_too_large" KindTimeout ErrorKind = "timeout" KindUnexpectedEOF ErrorKind = "unexpected_eof" KindEOF ErrorKind = "eof" KindClosed ErrorKind = "closed" KindOther ErrorKind = "other" )
The kinds that NetErrorKind returns, named after the classifier that matches each.
func NetErrorKind ¶
NetErrorKind returns the category of err: KindNone for nil, the kind of the first classifier that matches it, in the order of the constants, or KindOther.
type FramedConn ¶
type FramedConn struct {
// contains filtered or unexported fields
}
FramedConn reads and writes length-prefixed messages over a reliable stream.
Each frame is a 2-byte big-endian length followed by the payload. A frame is sent with one write of the connection, header and payload together (a vectored write on a *net.TCPConn), so a layer beneath, such as one that compresses or encrypts each write, sees whole frames; the bytes on the wire are the same however they are written.
By default the connection is a stream: Write sends p as one frame, or as several when it is longer than MaxFramePayload, which Reads join up again. Read it returns the current frame, or as much of it as fits in p, and a longer frame continues in the next Reads without being buffered. Empty frames are skipped, as they carry no stream bytes, and an error inside a frame splits it between two Reads.
With WithFramedDatagrams each frame is a message, as a datagram is: Write sends p as exactly one frame and fails with ErrFrameTooLarge for a longer one, and Read returns one frame per call. WriteFrame and ReadFrame work on one frame in either mode. WithFramedReadBuffer serves small frames or small buffers from one read of the connection.
An error that loses no frame bytes is returned unchanged and may be retried: one between frames or inside a frame header, such as an expired deadline, or, since stream Reads keep their place, one anywhere in a frame read by Read in stream mode. A ReadFrame or datagram Read that fails after part of the payload was read, the end of the stream inside a frame, and a write that fails after part of a frame was written lose the frame boundaries in that direction: they are reported as ErrFrameDesync wrapping their cause, which is not a timeout and is returned again by every later call in that direction.
Reads and writes may run concurrently with each other.
func NewFramedConn ¶
func NewFramedConn(c net.Conn, opts ...FramedOption) *FramedConn
NewFramedConn wraps c with length-prefixed message I/O.
func (*FramedConn) CloseWrite ¶
func (fc *FramedConn) CloseWrite() error
CloseWrite shuts down the writing side of the wrapped connection after the frames written so far; see TimeoutConn.CloseWrite.
func (*FramedConn) LocalAddr ¶
func (fc *FramedConn) LocalAddr() net.Addr
LocalAddr implements net.Conn.
func (*FramedConn) NetConn ¶
func (fc *FramedConn) NetConn() net.Conn
NetConn returns the connection that fc wraps, as *tls.Conn's NetConn does; see InnermostConn and ConnAs. Reading or writing it directly breaks the framing.
func (*FramedConn) NetxOwned ¶
func (fc *FramedConn) NetxOwned() OwnedLayers
NetxOwned describes the children closed with this layer.
func (*FramedConn) Read ¶
func (fc *FramedConn) Read(p []byte) (int, error)
Read reads frame payload into p.
In the default stream mode, a frame longer than p, or one whose reading an error interrupts, is returned across several Reads and empty frames are skipped; a Read that an error cuts short returns the bytes it read and leaves the error to the next Read. With WithFramedDatagrams, each call consumes exactly one frame, an empty one included, and discards what does not fit in p; an empty p consumes and discards one frame.
func (*FramedConn) ReadFrame ¶
func (fc *FramedConn) ReadFrame() ([]byte, error)
ReadFrame reads and returns one complete frame. If Read has already partially consumed a frame, ReadFrame returns the remaining bytes.
func (*FramedConn) RemoteAddr ¶
func (fc *FramedConn) RemoteAddr() net.Addr
RemoteAddr implements net.Conn.
func (*FramedConn) SetDeadline ¶
func (fc *FramedConn) SetDeadline(t time.Time) error
SetDeadline implements net.Conn.
func (*FramedConn) SetReadDeadline ¶
func (fc *FramedConn) SetReadDeadline(t time.Time) error
SetReadDeadline implements net.Conn.
func (*FramedConn) SetWriteDeadline ¶
func (fc *FramedConn) SetWriteDeadline(t time.Time) error
SetWriteDeadline implements net.Conn.
func (*FramedConn) Write ¶
func (fc *FramedConn) Write(p []byte) (int, error)
Write sends p as one frame. With stream reads, the default, a p longer than MaxFramePayload is sent as several frames, which the reader joins up again, so that io.Copy into a FramedConn works with any buffer; it returns the bytes of the frames sent whole. With WithFramedDatagrams, where each frame is a message, such a p fails with ErrFrameTooLarge, as WriteFrame does in both modes.
func (*FramedConn) WriteFrame ¶
func (fc *FramedConn) WriteFrame(p []byte) error
WriteFrame writes one complete frame.
type FramedOption ¶
type FramedOption func(*framedOptions)
FramedOption configures NewFramedConn.
func WithFramedDatagrams ¶
func WithFramedDatagrams() FramedOption
WithFramedDatagrams makes each frame a message, as a datagram is: Read returns exactly one frame per call, discarding the bytes that do not fit in p like a UDP socket truncating a datagram, and Write sends exactly one frame, failing for a payload longer than MaxFramePayload. ReadFrame and WriteFrame are not affected.
func WithFramedReadBuffer ¶
func WithFramedReadBuffer(size int) FramedOption
WithFramedReadBuffer reads the stream through a buffer of size bytes, so a burst of small frames costs one read of the wrapped connection instead of two per frame. Bytes already in the buffer are lost to anyone who reads the wrapped connection directly, for example through InnermostConn.
type NetErrorInfo ¶
type NetErrorInfo struct {
Kind ErrorKind
Err string // err.Error()
Local string // the connection's local address
Remote string // the connection's remote address
Op string // of the *net.OpError in the chain
Net string
Source string
Addr string
Syscall string // of the *os.SyscallError in the chain
ErrnoName string
// Errno is the platform errno in the chain, 0 for none, and ErrnoName
// its POSIX name for the errnos that the classifiers know (ECONNRESET
// also for WSAECONNRESET, for example), which depends on neither the
// platform nor the system language.
Errno int
Timeout bool
}
NetErrorInfo describes a network error for diagnostics; see NetErrorDetails. Empty fields are not known.
func NetErrorDetails ¶
func NetErrorDetails(err error, c net.Conn) NetErrorInfo
NetErrorDetails describes err, and the addresses of c if it is not nil, as fields, which String formats as one compact line for logs.
func (NetErrorInfo) String ¶
func (i NetErrorInfo) String() string
String formats i as space-separated key=value fields, such as `kind=conn_reset err="..." remote=192.0.2.1:443 timeout=false errno=104 errno_name=ECONNRESET`.
type OwnedLayers ¶
OwnedLayers describes the children closed by a wrapper. An external wrapper can implement NetxOwned() OwnedLayers. Set Self to the wrapper itself and First and Second to the children its Close owns. Leave unused children nil. A NetConn method alone exposes a borrowed connection.
type PrefixConn ¶
type PrefixConn struct {
// contains filtered or unexported fields
}
PrefixConn is a net.Conn whose reads return a prefix before the data of the connection it wraps. It hands a connection on after bytes were already read from it, for example to sniff the protocol. Writes, deadlines and addresses go to the wrapped connection.
func NewPrefixConn ¶
func NewPrefixConn(c net.Conn, prefix []byte) *PrefixConn
NewPrefixConn returns c with prefix replayed before its own data. prefix is not copied and must not be modified afterwards.
func (*PrefixConn) CloseWrite ¶
func (c *PrefixConn) CloseWrite() error
CloseWrite shuts down the writing side of the wrapped connection; see TimeoutConn.CloseWrite.
func (*PrefixConn) LocalAddr ¶
func (c *PrefixConn) LocalAddr() net.Addr
LocalAddr implements net.Conn.
func (*PrefixConn) NetConn ¶
func (c *PrefixConn) NetConn() net.Conn
NetConn returns the connection that c wraps, as *tls.Conn's NetConn does; see InnermostConn and ConnAs. Reading it directly skips the rest of the prefix.
func (*PrefixConn) NetxOwned ¶
func (c *PrefixConn) NetxOwned() OwnedLayers
NetxOwned describes the children closed with this layer.
func (*PrefixConn) RemoteAddr ¶
func (c *PrefixConn) RemoteAddr() net.Addr
RemoteAddr implements net.Conn.
func (*PrefixConn) SetDeadline ¶
func (c *PrefixConn) SetDeadline(t time.Time) error
SetDeadline implements net.Conn.
func (*PrefixConn) SetReadDeadline ¶
func (c *PrefixConn) SetReadDeadline(t time.Time) error
SetReadDeadline implements net.Conn.
func (*PrefixConn) SetWriteDeadline ¶
func (c *PrefixConn) SetWriteDeadline(t time.Time) error
SetWriteDeadline implements net.Conn.
type RaceDialer ¶
type RaceDialer struct {
// Dialers are the dialers to race, in order of preference; none means
// a zero net.Dialer.
Dialers []ContextDialer
// Stagger is how long an attempt runs alone before the next one
// starts, as in DialFirst; 0 means DefaultDialStagger (300ms), and a
// negative value starts the next only when one fails, as for
// net.Dialer.FallbackDelay.
Stagger time.Duration
}
RaceDialer races dial attempts with DialFirst: DialContext dials one address through each of its dialers, such as directly and through a relay or several proxies, and DialAny dials each of several addresses of a service, such as the entry points of a cluster, through each dialer. It is a ContextDialer, so that it can stand where one goes, such as an http.Transport's DialContext or a proxy dialer's Forward. The zero RaceDialer, and a nil one, dial with a zero net.Dialer and DefaultDialStagger. Its fields must not change while it dials.
func (*RaceDialer) DialAny ¶
func (d *RaceDialer) DialAny(ctx context.Context, network string, addresses ...string) (net.Conn, string, error)
DialAny dials addresses, in order of preference, through each of d's dialers, as DialFirst starts them: every dialer for the first address, then for the next. It returns the connection and the address that it connects to. When none connects, it returns ErrNoDialAttempts without addresses, ctx's error when ctx ended the dial, or else the errors of every attempt, joined, each naming its address.
func (*RaceDialer) DialContext ¶
DialContext dials address through each of d's dialers, as DialFirst starts them, and returns the first connection made. When none connects, it returns ctx's error when ctx ended the dial, or else the errors of every attempt, joined.
type ReadNotifier ¶
type ReadNotifier interface {
// TryRead reads as Read does but never blocks: while the source holds
// no data and has not ended or failed, it returns 0 and an error for
// which IsWouldBlock reports true: ErrWouldBlock, or an error of the
// source's own, possibly wrapped, with a method WouldBlock() bool that
// reports true. An error whose WouldBlock reports false is an ordinary
// error, as is any other.
// Otherwise it returns at once what Read would: n > 0 bytes, or 0 and
// io.EOF at the end of the stream, or 0 and the error Read would
// return. TryRead and Read share the source's data and are not called
// concurrently with each other, as Reads are not.
TryRead(p []byte) (n int, err error)
// NotifyReadable arranges for f to be called once the source is
// readable, and returns a function that cancels the call.
//
// f is called at most once, and exactly once unless stop cancels it
// first: when data arrives, at the end of the stream, on an error or a
// reset, when the source or the connection it belongs to is closed, and
// when a read deadline passes. A source that is readable when
// NotifyReadable is called calls f at once, without waiting for another
// event, possibly on the calling goroutine before NotifyReadable
// returns; a caller need not try TryRead first, and f must not wait for
// NotifyReadable to return.
//
// f may run on any goroutine, such as the one that reads the
// connection, and must not block; it may call the source's methods,
// so the source must not hold a lock of its own while it calls f.
//
// stop cancels the call as the stop of context.AfterFunc does: it
// returns true if it kept f from being called, and false if f has
// already been called or started, or the call was stopped already. stop
// does not wait for a running f to return, and calling it again is
// harmless.
//
// A source need support only one pending call at a time: a caller
// calls NotifyReadable again only after f has been called or stop
// returned true. Changing the read deadline does not affect a pending
// call beyond calling f when the deadline passes.
NotifyReadable(f func()) (stop func() bool)
}
ReadNotifier is a source that can be read without blocking and that tells when it becomes readable, such as a stream of a multiplexed connection. Relay copies from it without a goroutine of its own: no goroutine waits while the source is idle, and a short task, started by the notification, copies what there is and ends once TryRead would block. Copy waits on it before it takes a buffer, so that an idle copy holds none.
The source is readable once TryRead would return anything but an error for which IsWouldBlock reports true: data, the end of the stream after the peer closed its writing side, or an error, such as for a reset, a local Close or CloseRead, or a read deadline that has passed.
type RecordingConn ¶
type RecordingConn struct {
// contains filtered or unexported fields
}
RecordingConn records the bytes read from a connection, up to a limit, so that they can be replayed later, such as when a protocol was sniffed by reading it: Release returns the connection and the bytes, for a PrefixConn. For a single look at the first bytes, Peek is simpler.
func NewRecordingConn ¶
func NewRecordingConn(c net.Conn, limit int) *RecordingConn
NewRecordingConn wraps c and records up to limit read bytes, DefaultRecordingLimit if limit is not positive.
func (*RecordingConn) Buffered ¶
func (c *RecordingConn) Buffered() []byte
Buffered returns a copy of the bytes recorded so far.
func (*RecordingConn) CloseWrite ¶
func (c *RecordingConn) CloseWrite() error
CloseWrite shuts down the writing side of the underlying connection; see TimeoutConn.CloseWrite.
func (*RecordingConn) Discard ¶
func (c *RecordingConn) Discard()
Discard stops recording reads and frees what was recorded, such as once a sniffed protocol turned out not to need replaying.
func (*RecordingConn) LocalAddr ¶
func (c *RecordingConn) LocalAddr() net.Addr
LocalAddr implements net.Conn.
func (*RecordingConn) NetConn ¶
func (c *RecordingConn) NetConn() net.Conn
NetConn returns the connection that c wraps, or nil after Close or Release, as *tls.Conn's NetConn does; see InnermostConn and ConnAs.
func (*RecordingConn) NetxOwned ¶
func (c *RecordingConn) NetxOwned() OwnedLayers
NetxOwned describes the children closed with this layer.
func (*RecordingConn) Release ¶
func (c *RecordingConn) Release() (net.Conn, []byte)
Release detaches the underlying connection and returns it with a copy of the buffered bytes. During an active Read it returns (nil, nil) and keeps ownership, so a read callback can try Release without blocking. Retry once the Read returns to include its bytes. After a transfer the RecordingConn reports net.ErrClosed from Read, Write and the deadline methods, and its Close does not close the returned connection.
func (*RecordingConn) RemoteAddr ¶
func (c *RecordingConn) RemoteAddr() net.Addr
RemoteAddr implements net.Conn.
func (*RecordingConn) SetDeadline ¶
func (c *RecordingConn) SetDeadline(t time.Time) error
SetDeadline implements net.Conn.
func (*RecordingConn) SetReadDeadline ¶
func (c *RecordingConn) SetReadDeadline(t time.Time) error
SetReadDeadline implements net.Conn.
func (*RecordingConn) SetWriteDeadline ¶
func (c *RecordingConn) SetWriteDeadline(t time.Time) error
SetWriteDeadline implements net.Conn.
func (*RecordingConn) Stop ¶
func (c *RecordingConn) Stop()
Stop stops recording reads and keeps what was recorded, for Buffered and Release.
func (*RecordingConn) Truncated ¶
func (c *RecordingConn) Truncated() bool
Truncated reports whether reads went past the limit, so that the recorded bytes are not all that was read.
type RelayEnd ¶
type RelayEnd struct {
Reader io.Reader
Writer io.Writer
// CloseWriteFunc is called by CloseWrite, as with WithRelayHalfClose
// when the direction into this end ends; nil calls the CloseWrite
// method of Writer, if it has one.
CloseWriteFunc func() error
// CloseFunc is called by Close, as when the relay ends normally; nil
// closes Reader and Writer where they are io.Closers.
CloseFunc func() error
// AbortFunc is called by Abort, as when the relay stops on an error or
// because its context ended; it must end the reads and writes that
// block on the end. nil aborts what Reader and Writer read and write
// as Abort aborts a connection beneath its wrappers, an Aborter or a
// *net.TCPConn, and then calls Close.
AbortFunc func(cause error)
}
RelayEnd is an end of a Relay made of a reader and a writer, such as one side of a protocol exchange on a connection that carries more afterwards: Relay reads Reader and writes Writer as it would read and write them as ends of their own, looking through them for splice and its other fast paths, so that a part of a connection, such as an *io.LimitedReader over it or the parts of a ChainReader, is spliced where the connection would be. Reads, writes and closes go to the fields; it is not safe to change them while a Relay uses the end.
func (*RelayEnd) Abort ¶
Abort calls AbortFunc, or aborts what Reader and Writer read and write and then calls Close; see Aborter.
func (*RelayEnd) Close ¶
Close calls CloseFunc, or closes Reader and Writer. Values whose identity cannot be compared are closed separately.
func (*RelayEnd) CloseWrite ¶
CloseWrite calls CloseWriteFunc, or the CloseWrite method of Writer.
type RelayError ¶
RelayError is the error of a Relay that the failure of one direction stopped: From is the end whose data that direction copied, so that the error is one of reading From, of writing From.Other(), or of the RelayFlow of that direction. Err is the error itself, which errors.Is and errors.As find through it. Whether it was the read or the write is told by Err where it is a *net.OpError; Relay does not take its fast paths apart to tell it otherwise.
func (*RelayError) Error ¶
func (e *RelayError) Error() string
type RelayFlow ¶
type RelayFlow struct {
// Wait is called before each read from the direction's source with the
// most bytes Relay can take at once, and blocks until bytes may pass. It
// returns how many may pass now, from 1 to n: a stream is read for at
// most that many, and a datagram is read whole, as it cannot be split.
// On Unix systems, a source read straight from a socket is waited on
// until it has data first, and its end is passed on without Wait; for
// other sources Wait runs while they may still be idle, and before the
// read that finds their end. A blocked Wait holds none of Relay's
// buffers or pipes. A Wait that may block for long must return when ctx
// is done: closing the relay's ends does not wake it, so end such relays
// with Relay's context or WithRelayGroup.
// Wait need not charge them, since Done reports what passed: a limiter
// can charge that, going into debt that a later Wait waits out, so that
// a relay idle in a read holds none of an allowance it shares. ctx is
// done once the relay stops. An error ends the relay and is returned.
Wait func(ctx context.Context, n int64) (int64, error)
// Done is called with the bytes written to the direction's destination
// after each write. An error, such as for a used up allowance, ends the
// relay and is returned.
Done func(n int64) error
// First is called once with the first bytes read from the direction's
// source, a stream's first non-empty read or the first datagram, before
// they are written, so that a relay can tell the protocol of a
// connection or log the start of it. b is valid only during the call.
// A stream's first read goes through Relay's buffer, also where Relay
// splices the rest.
First func(b []byte)
// End is called once when the direction stops, with the bytes it
// copied and the error that stopped it: nil at the source's EOF, or
// net.ErrClosed when the relay stopped it for another reason, such as
// the other direction ending. Relay calls it before it passes the end on
// with CloseWrite or stops the relay, so that the other direction can
// be given a shorter idle timeout once one has ended, and Copy before it
// returns. Unlike the other hooks, End alone does not make a direction
// go through Relay's buffer.
End func(n int64, err error)
}
RelayFlow paces and counts one direction of a Relay or a Copy. Any of its functions may be nil. They are called from the goroutine copying that direction, one call at a time; functions shared by both directions, or by several relays, as a limiter of one user is, must be safe for concurrent use.
type RelayOption ¶
type RelayOption func(*relayOptions)
RelayOption configures Relay.
func WithRelayClock ¶
func WithRelayClock(c timeshim.Clock) RelayOption
WithRelayClock makes the idle timeout of WithRelayIdleTimeout tell the time by c instead of the system clock, such as a timeshim.Fake in tests.
func WithRelayFlows ¶
func WithRelayFlows(aToB, bToA *RelayFlow) RelayOption
WithRelayFlows paces and counts the two directions of a Relay, from a to b and from b to a; see RelayFlow. A nil flow does neither, and the flows are copied, so that changing them later does not affect the relay. A direction whose flow has Wait, Done or First is copied with splice where Relay would splice it, in pieces, so that Done sees the bytes as they pass, and otherwise through Relay's buffer: the reading end's WriteTo and the writing end's ReadFrom are not used, so only the sources that Relay knows to return one datagram per Read are read a datagram at a time.
Example ¶
Count what a relay passes and end it from outside, as when an allowance runs out.
package main
import (
"context"
"errors"
"fmt"
"io"
"net"
"github.com/djylb/netx"
)
func main() {
client, front := net.Pipe()
back, backend := net.Pipe()
go func() { _, _ = io.Copy(backend, backend) }()
var counted int64
count := netx.RelayFlow{Done: func(n int64) error {
counted += n
return nil
}}
ctx, cancel := context.WithCancelCause(context.Background())
done := make(chan error)
go func() {
_, _, err := netx.Relay(ctx, front, back, netx.WithRelayFlows(&count, nil))
done <- err
}()
_, _ = client.Write([]byte("ping"))
_, _ = io.ReadFull(client, make([]byte, 4))
cancel(errors.New("allowance used up"))
err := <-done
fmt.Println(err, counted)
}
Output: allowance used up 4
Example (Limit) ¶
Limit the bandwidth that a user's relays share.
package main
import (
"context"
"fmt"
"io"
"net"
"sync"
"time"
"github.com/djylb/netx"
)
// byteLimiter is a shared bandwidth limit for RelayFlow: Done charges what
// passed, which may put the limiter in debt, and Wait waits the debt out, so
// a relay idle in a read holds none of the allowance. It is safe for
// concurrent use by many relays.
type byteLimiter struct {
last time.Time // under mu
rate float64 // bytes per second
burst float64
tokens float64
mu sync.Mutex
}
func newByteLimiter(bytesPerSecond, burst int64) *byteLimiter {
return &byteLimiter{rate: float64(bytesPerSecond), burst: float64(burst), tokens: float64(burst), last: time.Now()}
}
// refill adds the tokens earned since the last call; l.mu is held.
func (l *byteLimiter) refill(now time.Time) {
l.tokens = min(l.burst, l.tokens+now.Sub(l.last).Seconds()*l.rate)
l.last = now
}
// Wait blocks while the limiter is in debt and then lets up to n bytes pass.
func (l *byteLimiter) Wait(ctx context.Context, n int64) (int64, error) {
for {
l.mu.Lock()
l.refill(time.Now())
if l.tokens >= 1 {
allowed := min(n, int64(l.tokens))
l.mu.Unlock()
return allowed, nil
}
wait := time.Duration((1 - l.tokens) / l.rate * float64(time.Second))
l.mu.Unlock()
t := time.NewTimer(wait)
select {
case <-ctx.Done():
t.Stop()
return 0, ctx.Err()
case <-t.C:
}
}
}
// Done charges the bytes that passed.
func (l *byteLimiter) Done(n int64) error {
l.mu.Lock()
l.refill(time.Now())
l.tokens -= float64(n)
l.mu.Unlock()
return nil
}
// Limit the bandwidth that a user's relays share.
func main() {
user := newByteLimiter(64<<10, 16<<10) // 64 KiB/s, bursts of 16 KiB
flow := netx.RelayFlow{Wait: user.Wait, Done: user.Done}
client, front := net.Pipe()
back, backend := net.Pipe()
go func() { _, _ = io.Copy(io.Discard, backend) }()
go func() { _, _, _ = netx.Relay(context.Background(), front, back, netx.WithRelayFlows(&flow, &flow)) }()
start := time.Now()
_, _ = client.Write(make([]byte, 48<<10)) // 16 KiB at once, then 32 KiB at 64 KiB/s
_ = client.Close()
fmt.Println(time.Since(start) >= 400*time.Millisecond)
}
Output: true
func WithRelayGroup ¶
func WithRelayGroup(groups ...*ConnGroup) RelayOption
WithRelayGroup adds the relay to each group while it runs: the group's CloseMembers and Close end it as the end of Relay's context would, also while a RelayFlow.Wait blocks, which closing the relay's ends cannot do, and Relay returns ErrRelayGroupClosed, which also matches the cause given to CloseMembers. A relay started on a closed group ends at once.
func WithRelayHalfClose ¶
func WithRelayHalfClose() RelayOption
WithRelayHalfClose makes Relay pass EOF on instead of ending the relay: when one direction reaches EOF, Relay shuts down the writing side of the other end with CloseWrite and keeps copying the opposite direction until it ends too. An end without CloseWrite support, such as a net.Pipe, is closed as without this option. Pair it with an idle timeout, for example TimeoutConn, so a peer that never finishes cannot hold the relay open.
func WithRelayIdleTimeout ¶
func WithRelayIdleTimeout(d time.Duration) RelayOption
WithRelayIdleTimeout ends the relay once no data has passed in either direction for d, and Relay then returns ErrRelayIdle. Relay watches the data it copies, also where it splices, and leaves the ends' deadlines alone, so it works on ends without deadlines too; time spent in a RelayFlow.Wait does not count as idle. The idle timeout keeps the fast paths of a direction without RelayFlow hooks: splice, in pieces, and the ends' own WriteTo and ReadFrom, through a writer or reader that records the data. A non-positive d sets none.
type RelaySide ¶
type RelaySide uint8
RelaySide names an end of a Relay: RelayA is its argument a, RelayB its argument b.
type Scope ¶
type Scope uint8
Scope is the reachability class of an IP address, as the IANA IPv4 and IPv6 Special-Purpose Address Registries (RFC 6890 and its updates) and the address architectures (RFC 791, RFC 4291) assign it. ScopeOf returns it.
const ( // ScopeInvalid is the scope of the zero netip.Addr. ScopeInvalid Scope = iota // ScopeUnspecified is 0.0.0.0 and ::, which name no host but reach the // local host on many systems when dialed. ScopeUnspecified // ScopeLoopback is 127.0.0.0/8 and ::1. ScopeLoopback // ScopeLinkLocal is 169.254.0.0/16 and fe80::/10. ScopeLinkLocal // ScopePrivate is the space of private networks: 10.0.0.0/8, // 172.16.0.0/12, 192.168.0.0/16 (RFC 1918), the unique local addresses // fc00::/7 (RFC 4193) and the local-use translation prefix // 64:ff9b:1::/48 (RFC 8215). ScopePrivate // NAT (RFC 6598). ScopeShared // ScopeMulticast is 224.0.0.0/4 and ff00::/8, of any multicast scope. ScopeMulticast // ScopeBroadcast is the limited broadcast address 255.255.255.255. ScopeBroadcast // ScopeDocumentation is 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24 // (RFC 5737), 2001:db8::/32 (RFC 3849) and 3fff::/20 (RFC 9637). ScopeDocumentation // ScopeBenchmarking is 198.18.0.0/15 (RFC 2544) and 2001:2::/48 // (RFC 5180). ScopeBenchmarking // ScopeReserved is unicast space that is not globally reachable and // has none of the uses above: "this network" 0.0.0.0/8, the IETF // protocol assignments 192.0.0.0/24 and 2001::/23 apart from their // globally reachable entries, the former 6to4 relay anycast // 192.88.99.0/24 (RFC 7526), 240.0.0.0/4, the discard and dummy // prefixes 100::/64 and 100:0:0:1::/64, the deprecated ORCHID // 2001:10::/28, the segment routing SIDs 5f00::/16, IPv6 outside // 2000::/3 that no entry names (such as the deprecated site-local // fec0::/10 and the IPv4-compatible ::/96), and translation addresses // that embed an IPv4 address that is not global (see ScopeOf). ScopeReserved // ScopeGlobal is globally reachable unicast. ScopeGlobal )
Scopes, from the narrowest to the widest reach.
func ScopeOf ¶
ScopeOf returns the scope of a, ignoring its zone. An IPv4-mapped IPv6 address has the scope of its IPv4 address.
The registries leave the reachability of 6to4 (2002::/16) and Teredo (2001::/32) addresses to the IPv4 addresses they embed, so such an address is ScopeGlobal when its embedded IPv4 addresses are (for Teredo, the server's and the client's) and ScopeReserved otherwise. The NAT64 well-known prefix 64:ff9b::/96 is globally reachable in the registry, and RFC 6052 forbids it to embed an IPv4 address that is not global, so its addresses are classified in the same way, which agrees with the registry for every valid one. The RFC 8215 local-use prefix 64:ff9b:1::/48 is ScopePrivate whatever it embeds.
Registry entries that are globally reachable inside larger reserved blocks, such as the PCP and TURN anycast addresses 192.0.0.9, 192.0.0.10, 2001:1::1 and 2001:1::2, are ScopeGlobal. Multicast addresses are ScopeMulticast whatever their multicast scope. ScopeOf does not allocate.
Example ¶
Classify addresses before offering them to peers on the Internet.
package main
import (
"fmt"
"net/netip"
"github.com/djylb/netx"
)
func main() {
for _, s := range []string{"203.0.113.7", "100.72.1.2", "::ffff:192.168.1.10", "2002:808:808::1", "2606:4700::1111"} {
a := netip.MustParseAddr(s)
fmt.Println(s, netx.ScopeOf(a), netx.IsGlobal(a))
}
}
Output: 203.0.113.7 documentation false 100.72.1.2 shared false ::ffff:192.168.1.10 private false 2002:808:808::1 global true 2606:4700::1111 global true
type SingleConnListener ¶
type SingleConnListener struct {
// contains filtered or unexported fields
}
SingleConnListener is the listener that NewSingleConnListener returns. The zero value has no connection: its Accept blocks until Close.
func NewSingleConnListener ¶
func NewSingleConnListener(c net.Conn) *SingleConnListener
NewSingleConnListener returns a listener whose first Accept returns c. Later Accept calls block until that connection or the listener is closed and then return net.ErrClosed, so a server loop such as http.Server.Serve handles c and returns when it is done.
Accept returns c wrapped so that its Close can be observed; InnermostConn unwraps it. The wrapper hides c's concrete type, so to serve TLS pass the plain connection and wrap the listener with tls.NewListener.
The connection belongs to the server once Accept has returned it: Close closes c only if Accept has not returned it yet, and otherwise only ends a blocked Accept, so closing the listener does not cut off the connection being served. To stop serving it, close the connection, or shut the server down, as http.Server.Shutdown does for its connections; Serve returns once the connection is closed.
Example ¶
Run an http.Server on one connection; Serve returns once it is closed.
package main
import (
"bufio"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"github.com/djylb/netx"
)
func main() {
client, server := net.Pipe()
served := make(chan error, 1)
go func() {
served <- http.Serve(netx.NewSingleConnListener(server), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprint(w, "ok")
}))
}()
req, _ := http.NewRequest(http.MethodGet, "http://single/", nil)
req.Close = true // the server closes the connection after the response
go func() { _ = req.Write(client) }()
resp, err := http.ReadResponse(bufio.NewReader(client), req)
if err != nil {
log.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
fmt.Println(errors.Is(<-served, net.ErrClosed))
}
Output: ok true
Example (Shutdown) ¶
Serve one connection with an http.Server and stop it from outside: closing the listener would leave the connection being served alone, so Shutdown, which closes the server's connections once idle, or Close ends it.
package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"time"
"github.com/djylb/netx"
)
func main() {
client, server := net.Pipe()
defer func() { _ = client.Close() }()
srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})}
served := make(chan error, 1)
go func() { served <- srv.Serve(netx.NewSingleConnListener(server)) }()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
fmt.Println(errors.Is(<-served, http.ErrServerClosed))
}
Output: true
func (*SingleConnListener) Accept ¶
func (l *SingleConnListener) Accept() (net.Conn, error)
Accept returns the connection the first time and then blocks until it or l is closed, returning net.ErrClosed.
func (*SingleConnListener) Addr ¶
func (l *SingleConnListener) Addr() net.Addr
Addr returns the connection's LocalAddr, or "pipe" if it has none.
func (*SingleConnListener) Close ¶
func (l *SingleConnListener) Close() error
Close ends a blocked Accept and closes the connection if Accept has not returned it yet.
type TimeoutConn ¶
type TimeoutConn struct {
// contains filtered or unexported fields
}
TimeoutConn closes an idle connection: before each read or write it moves the deadline of both directions to now plus the idle timeout. Construct it with NewTimeoutConn; SetIdleTimeout changes the timeout later, such as from a short one for a handshake to a longer one once it is done. A non-positive idle timeout sets none.
To keep the per-call cost to an atomic load, a read or write moves the deadline only once less than the idle timeout is left, and then to now plus the idle timeout and a small slack (idle/16, at most one second). A connection therefore never times out before it has been idle for the idle timeout, and at most that slack later.
SetDeadline, SetReadDeadline and SetWriteDeadline are remembered until they are changed again. Setting them and every read and write keep each direction's deadline at the earlier of the remembered one and now plus the idle timeout, so a deadline set to interrupt a blocked Read or Write stays in effect while the other direction is in use, and a later or zero one does not lift the idle timeout of a Read or Write that is already blocked. A zero time leaves only the idle timeout.
func NewTimeoutConn ¶
func NewTimeoutConn(c net.Conn, idle time.Duration) *TimeoutConn
NewTimeoutConn wraps c and refreshes its deadline before each read or write, so that it times out after idle without either; a non-positive idle sets no idle timeout.
func (*TimeoutConn) CloseWrite ¶
func (c *TimeoutConn) CloseWrite() error
CloseWrite shuts down the writing side of the wrapped connection, so the peer reads EOF while reads continue. It returns an error matching errors.ErrUnsupported when the wrapped connection cannot do that.
func (*TimeoutConn) IdleTimeout ¶
func (c *TimeoutConn) IdleTimeout() time.Duration
IdleTimeout returns the idle timeout; see SetIdleTimeout.
func (*TimeoutConn) LocalAddr ¶
func (c *TimeoutConn) LocalAddr() net.Addr
LocalAddr implements net.Conn.
func (*TimeoutConn) NetConn ¶
func (c *TimeoutConn) NetConn() net.Conn
NetConn returns the connection that c wraps, as *tls.Conn's NetConn does; see InnermostConn and ConnAs. Its reads and writes do not refresh the idle timeout.
func (*TimeoutConn) NetxOwned ¶
func (c *TimeoutConn) NetxOwned() OwnedLayers
NetxOwned describes the children closed with this layer.
func (*TimeoutConn) RemoteAddr ¶
func (c *TimeoutConn) RemoteAddr() net.Addr
RemoteAddr implements net.Conn.
func (*TimeoutConn) SetDeadline ¶
func (c *TimeoutConn) SetDeadline(t time.Time) error
SetDeadline implements net.Conn.
func (*TimeoutConn) SetIdleTimeout ¶
func (c *TimeoutConn) SetIdleTimeout(d time.Duration) error
SetIdleTimeout changes the idle timeout, also of a Read or Write already blocked; a non-positive d removes it, leaving the deadlines that were set.
func (*TimeoutConn) SetReadDeadline ¶
func (c *TimeoutConn) SetReadDeadline(t time.Time) error
SetReadDeadline implements net.Conn.
func (*TimeoutConn) SetWriteDeadline ¶
func (c *TimeoutConn) SetWriteDeadline(t time.Time) error
SetWriteDeadline implements net.Conn.
type WrapOption ¶
type WrapOption func(*wrapOptions)
WrapOption configures WrapConn.
func WithWrapParentClose ¶
func WithWrapParentClose() WrapOption
WithWrapParentClose makes WrapConn close parent after closing rwc. parent is skipped when rwc already owns it, and net.ErrClosed from parent is ignored because rwc may already have closed it.
Source Files
¶
- abort.go
- addr.go
- bufpool.go
- conn_addr.go
- conn_forward.go
- conn_framed.go
- conn_group.go
- conn_layers.go
- conn_prefix.go
- conn_recording.go
- conn_timeout.go
- conn_traffic.go
- conn_wrap.go
- ctxio.go
- dial.go
- doc.go
- errno_name.go
- errno_posix.go
- errors.go
- iox.go
- listener.go
- listener_accept.go
- relay.go
- relay_copy.go
- relay_end.go
- relay_flow.go
- relay_notify.go
- relay_parts.go
- relay_socket_unix.go
- relay_splice_linux.go
- scope.go
- udp.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package duplex joins a read half and a write half into a net.Conn, and lets either half be replaced while the connection is in use.
|
Package duplex joins a read half and a write half into a net.Conn, and lets either half be replaced while the connection is in use. |
|
Package forwarded finds the address of the client of an HTTP request that came through proxies, from the X-Forwarded-For, X-Real-IP or Forwarded (RFC 7239) header fields that the proxies add, and formats those fields for a proxy to pass on.
|
Package forwarded finds the address of the client of an HTTP request that came through proxies, from the X-Forwarded-For, X-Real-IP or Forwarded (RFC 7239) header fields that the proxies add, and formats those fields for a proxy to pass on. |
|
Package httphead reads and parses the heads of HTTP/1.x messages, the start line and the header fields, strictly where a lax reading lets two parties read one message in two ways, as in request smuggling, and leniently where that is safe (RFC 9110, RFC 9112).
|
Package httphead reads and parses the heads of HTTP/1.x messages, the start line and the header fields, strictly where a lax reading lets two parties read one message in two ways, as in request smuggling, and leniently where that is safe (RFC 9110, RFC 9112). |
|
Package httpproxy implements an HTTP proxy server: CONNECT tunnels and forwarding of absolute-form requests such as "GET http://host/path", over any net.Conn, with optional Basic proxy authentication.
|
Package httpproxy implements an HTTP proxy server: CONNECT tunnels and forwarding of absolute-form requests such as "GET http://host/path", over any net.Conn, with optional Basic proxy authentication. |
|
Package httprewrite rewrites the header fields of HTTP requests and responses with templates, for reverse proxies and servers: templates such as "${scheme}://${host}${request_uri}" in the style of the variables of common reverse proxies are compiled once and expanded per request, rule lists set, add and delete request and response fields, and redirects in Location and Refresh are rewritten from the backend's address to the public one.
|
Package httprewrite rewrites the header fields of HTTP requests and responses with templates, for reverse proxies and servers: templates such as "${scheme}://${host}${request_uri}" in the style of the variables of common reverse proxies are compiled once and expanded per request, rule lists set, add and delete request and response fields, and redirects in Location and Refresh are rewritten from the backend's address to the public one. |
|
internal
|
|
|
bufpool
Package bufpool holds buffers shared by networking helpers.
|
Package bufpool holds buffers shared by networking helpers. |
|
clock
Package clock provides clocks, timers and timing helpers for network I/O.
|
Package clock provides clocks, timers and timing helpers for network I/O. |
|
creds
Package creds checks user names and passwords against a fixed account list for the servers of this module.
|
Package creds checks user names and passwords against a fixed account list for the servers of this module. |
|
dgram
Package dgram provides bounded queues for datagram connections.
|
Package dgram provides bounded queues for datagram connections. |
|
dnslookup
Package dnslookup resolves names and queues datagrams pending resolution.
|
Package dnslookup resolves names and queues datagrams pending resolution. |
|
flowtable
Package flowtable manages datagram flow registration, acceptance and expiry.
|
Package flowtable manages datagram flow registration, acceptance and expiry. |
|
leakcheck
Package leakcheck checks test binaries for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first, and VerifyTestMain fails a whole test binary with them.
|
Package leakcheck checks test binaries for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first, and VerifyTestMain fails a whole test binary with them. |
|
nettest
Package nettest holds helpers shared by the tests of netx packages.
|
Package nettest holds helpers shared by the tests of netx packages. |
|
netutil
Package netutil holds the small helpers that the packages of this module share: address normalisation, the splice decision, the ContextDialer interface and the A-labels of internationalised names.
|
Package netutil holds the small helpers that the packages of this module share: address normalisation, the splice decision, the ContextDialer interface and the A-labels of internationalised names. |
|
serve
Package serve holds the lifecycle that the servers of this module share: the listeners and connections they serve, a context that Close cancels, Shutdown and Close.
|
Package serve holds the lifecycle that the servers of this module share: the listeners and connections they serve, a context that Close cancels, Shutdown and Close. |
|
Package memnet is an in-process network for tests: stream listeners and connections that behave like TCP sockets (buffered in both directions, half-close, reset on SetLinger(0), deadlines), packet endpoints that deliver whole datagrams and drop them when full, a resolver, dials from a chosen source host, and fault injection per address and direction: delay, rate, loss and cut links, driven by an injectable clock and randomness source.
|
Package memnet is an in-process network for tests: stream listeners and connections that behave like TCP sockets (buffered in both directions, half-close, reset on SetLinger(0), deadlines), packet endpoints that deliver whole datagrams and drop them when full, a resolver, dials from a chosen source host, and fault injection per address and direction: delay, rate, loss and cut links, driven by an injectable clock and randomness source. |
|
Package proxydial dials TCP connections through HTTP CONNECT, SOCKS5 and SOCKS4 proxies, in the clear or over TLS.
|
Package proxydial dials TCP connections through HTTP CONNECT, SOCKS5 and SOCKS4 proxies, in the clear or over TLS. |
|
Package proxyproto builds and decodes PROXY protocol v1 and v2 headers, which carry the original client and destination addresses of a proxied connection to the backend, and provides a Conn that reports those addresses for a connection whose peer sends one, with a Listener that wraps the connections it accepts.
|
Package proxyproto builds and decodes PROXY protocol v1 and v2 headers, which carry the original client and destination addresses of a proxied connection to the backend, and provides a Conn that reports those addresses for a connection whose peer sends one, with a Listener that wraps the connections it accepts. |
|
Package safedial dials, and sends datagrams to, only the destinations that a policy allows, for a program that connects on behalf of a party it trusts less: a tunnel client that a server tells where to connect, a proxy, or a sender of webhooks to URLs that users give.
|
Package safedial dials, and sends datagrams to, only the destinations that a policy allows, for a program that connects on behalf of a party it trusts less: a tunnel client that a server tells where to connect, a proxy, or a sender of webhooks to URLs that users give. |
|
Package socks5 implements SOCKS version 5 (RFC 1928) with username/password authentication (RFC 1929): a message codec for clients and servers, and a configurable Server.
|
Package socks5 implements SOCKS version 5 (RFC 1928) with username/password authentication (RFC 1929): a message codec for clients and servers, and a configurable Server. |
|
Package tlsconn runs TLS handshakes over existing connections with a bound on how long they take, and provides a Dialer that layers TLS on any dialer, such as a proxy dialer.
|
Package tlsconn runs TLS handshakes over existing connections with a bound on how long they take, and provides a Dialer that layers TLS on any dialer, such as a proxy dialer. |
|
Package transparent accepts TCP connections and UDP datagrams that a transparent proxy setup redirects to a local socket, and recovers the destination they were addressed to.
|
Package transparent accepts TCP connections and UDP datagrams that a transparent proxy setup redirects to a local socket, and recovers the destination they were addressed to. |
|
Package udpflow turns UDP datagrams into connections that can be accepted from or dialed through a shared packet socket.
|
Package udpflow turns UDP datagrams into connections that can be accepted from or dialed through a shared packet socket. |
|
Package wsconn implements the WebSocket protocol (RFC 6455) for tunnels, proxies and message channels: the opening handshake on both sides, a message API, and a net.Conn that carries a byte stream over binary messages.
|
Package wsconn implements the WebSocket protocol (RFC 6455) for tunnels, proxies and message channels: the opening handshake on both sides, a message API, and a net.Conn that carries a byte stream over binary messages. |
|
wshttp
Package wshttp connects package wsconn to net/http: Upgrade and Serve turn the requests of a handler into WebSocket connections, Check and Accept do the same in two steps for a handler that decides on a request before anything is answered, and Dialer dials WebSocket over HTTP/2.
|
Package wshttp connects package wsconn to net/http: Upgrade and Serve turn the requests of a handler into WebSocket connections, Check and Accept do the same in two steps for a handler that decides on a request before anything is answered, and Dialer dials WebSocket over HTTP/2. |