netrelay

package
v0.71.2 Latest Latest
Warning

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

Go to latest
Published: May 16, 2026 License: BSD-3-Clause Imports: 8 Imported by: 0

Documentation

Overview

Package netrelay provides a bidirectional byte-copy helper for TCP-like connections with correct half-close propagation.

When one direction reads EOF, the write side of the opposite connection is half-closed (CloseWrite) so the peer sees FIN, then the second direction is allowed to drain to its own EOF before both connections are fully closed. This preserves TCP half-close semantics (e.g. shutdown(SHUT_WR)) that the naive "cancel-both-on-first-EOF" pattern breaks.

Index

Constants

View Source
const DefaultIdleTimeout = 5 * time.Minute

DefaultIdleTimeout is a reasonable default for Options.IdleTimeout. Callers that want an idle timeout but have no specific preference can use this.

Variables

This section is empty.

Functions

func Relay

func Relay(ctx context.Context, a, b io.ReadWriteCloser, opts Options) (aToB, bToA int64)

Relay copies bytes in both directions between a and b until both directions EOF or ctx is canceled. On each direction's EOF it half-closes the opposite conn's write side (best effort) so the peer sees FIN while the other direction drains. Both conns are fully closed when Relay returns.

a and b only need to implement io.ReadWriteCloser; connections that also implement CloseWrite (e.g. *net.TCPConn, ssh.Channel) get proper half-close propagation. Options.IdleTimeout, when set, is enforced by a connection-wide watchdog that tracks reads in either direction.

Return values are byte counts: aToB (a.Read → b.Write) and bToA (b.Read → a.Write). Errors are logged via Options.Logger when set; they are not returned because a relay always terminates on some kind of EOF/cancel.

Types

type DebugLogger

type DebugLogger interface {
	Debugf(format string, args ...any)
}

DebugLogger is the minimal interface netrelay uses to surface teardown errors. Both *logrus.Entry and *nblog.Logger (via its Debugf method) satisfy it, so callers can pass whichever they already use without an adapter. Debugf is the only required method; callers with richer loggers just expose this one shape here.

type Options

type Options struct {
	// IdleTimeout tears down the session if no bytes flow in either
	// direction within this window. It is a connection-wide watchdog, so a
	// long unidirectional transfer on one side keeps the other side alive.
	// Zero disables idle tracking.
	IdleTimeout time.Duration
	// Logger receives debug-level copy/idle errors. Nil suppresses logging.
	// Any logger with Debug/Debugf methods is accepted (logrus.Entry,
	// uspfilter's nblog.Logger, etc.).
	Logger DebugLogger
}

Options configures Relay behavior. The zero value is valid: no idle timeout, no logging.

Jump to

Keyboard shortcuts

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