conn

package
v0.35.6 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: GPL-3.0 Imports: 36 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	TransportTCP  = "tcp"
	TransportKCP  = "kcp"
	TransportQUIC = "quic"
	TransportTLS  = "tls"
	TransportWS   = "ws"
	TransportWSS  = "wss"
)

Transports a client connects to the bridge with.

View Source
const (
	LinkTCP  = "tcp"
	LinkUDP  = "udp"
	LinkUDP5 = "udp5" // SOCKS5 datagrams with their headers
	LinkPing = "ping"
)

Kinds of the links a tunnel opens, as Link.ConnType names them.

View Source
const HandshakeTimeout = 10 * time.Second

HandshakeTimeout bounds how long an accepted transport may take to present its first stream or protocol upgrade before it is dropped.

Variables

View Source
var (
	BufPool     = newBytePool64K()
	BufPoolCopy = newBytePoolCopy()
)

Shared buffer pools: BufPool for packets and relays, BufPoolCopy for the copy buffers of reverse proxies.

View Source
var (
	ErrFlowLimit = errors.New("flow limit exceeded")
	ErrTimeLimit = errors.New("time limit exceeded")
)

ErrFlowLimit and ErrTimeLimit are matched by the errors of a task or client over its traffic limit or past its time limit.

View Source
var LocalTCPAddr = &net.TCPAddr{IP: net.ParseIP("127.0.0.1")}

Functions

func Accept

func Accept(l net.Listener, f func(c net.Conn)) error

Accept serves l until it is closed or fails; netx.Accept retries transient errors with a backoff. Accept hands every connection l accepts to f until l fails or is closed. It returns nil once l is closed and the accept error otherwise.

func AcceptQuicStream added in v0.35.0

func AcceptQuicStream(sess *quic.Conn, f func(c net.Conn))

AcceptQuicStream hands the first stream of sess to f, or closes sess when none comes in time.

func CheckFlowLimits added in v0.29.25

func CheckFlowLimits(f Flow, label string) error

CheckFlowLimits returns an error naming label, matching ErrFlowLimit or ErrTimeLimit, if f is over its traffic limit or past its time limit.

func CopyWaitGroup

func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rt *rate.Rate,
	flows []Flow, cert *tls.Certificate, proxyProtocol int, rb []byte, task Entry, isLocal, isFramed bool) (out, in int64)

CopyWaitGroup relays between conn1, a link to an npc, and conn2. cert is the certificate of the side that opened the link, as for LinkConn; the limits of task apply on that side only. It returns the bytes written out to conn2 and read in from it.

func DialKCPWithLocalIP added in v0.34.6

func DialKCPWithLocalIP(raddr string, localIP string) (*kcp.UDPSession, error)

DialKCPWithLocalIP creates a KCP connection with optional local IP binding.

func DialProxy added in v0.35.0

func DialProxy(proxyUrl, server string, timeout time.Duration, localIP string) (net.Conn, error)

DialProxy dials server directly, through proxyUrl, or through the proxy configured in ALL_PROXY and NO_PROXY. proxyUrl may use the http, https, socks5, socks5h, socks4 and socks4a schemes, or be a bare host:port, which is taken as an http proxy. The whole dial, including any proxy handshake, is bounded by timeout.

func DialQuicWithLocalIP added in v0.34.7

func DialQuicWithLocalIP(ctx context.Context, server string, tlsCfg *tls.Config, quicCfg *quic.Config, localIP string) (*quic.Conn, error)

func DialVirtual added in v0.34.8

func DialVirtual(ctx context.Context, l *netx.ChanListener, remote string) (net.Conn, error)

DialVirtual connects to l through an in-memory pipe, with remote, a host:port address, as the address of the dialing side. It waits for queue space until ctx is done or l is closed.

func DialWS added in v0.27.0

func DialWS(rawConn net.Conn, urlStr, host string, timeout time.Duration) (net.Conn, error)

DialWS runs the WebSocket opening handshake for urlStr over rawConn, which already carries TLS for a wss URL, sending host as the Host field when it is set, and returns the byte stream over the connection's messages. On failure rawConn is closed.

func GetConn

func GetConn(conn net.Conn, cpt, snappy bool, rt *rate.Rate, cert *tls.Certificate, isLocal bool, entry ...*rate.Directional) io.ReadWriteCloser

GetConn returns LinkConn of conn limited and counted by rt and entry, as rate.NewRateConn does.

func HandleUdp5 added in v0.30.6

func HandleUdp5(ctx context.Context, serverConn net.Conn, timeout time.Duration, localIP string)

HandleUdp5 relays the SOCKS5 UDP datagrams of serverConn, one per frame, through a local UDP socket bound to localIP, if it is an IP address: each datagram's payload goes to its destination, and each datagram received goes back with its source as the address. It returns, closing serverConn, when ctx ends, either side closes or fails, or no datagram passed in either direction for timeout.

func HandleUdp5Policy added in v0.35.0

func HandleUdp5Policy(ctx context.Context, serverConn net.Conn, timeout time.Duration, localIP string, allow UDP5Policy)

HandleUdp5Policy is HandleUdp5 dropping the datagrams allow refuses; nil allows all. A name is sent to the address it was judged by.

func Join added in v0.34.8

func Join(visitor, client net.Conn, flows []Flow, task Entry, remote string) (out, in int64)

Join relays between visitor and the connection to the client until either direction ends, then closes both. Each of flows counts the bytes from the visitor as inlet and those back as export traffic, and the relay stops once one of them is over its limits; the first bytes of each direction set task.IsHttp. It returns the bytes written out to the visitor and read in from it.

func LinkConn added in v0.35.0

func LinkConn(conn net.Conn, cpt, snappy bool, cert *tls.Certificate, isLocal bool) io.ReadWriteCloser

LinkConn wraps conn, a link to an npc, with its encryption or compression; a local link is used as it is. cert is the certificate of the side that opened the link, the TLS server of an encrypted link; it is nil on the side that accepted it.

func ListenKCP added in v0.35.0

func ListenKCP(addr string) (*kcp.Listener, error)

ListenKCP opens the KCP listener of the bridge on addr.

func ListenKCPOn added in v0.35.0

func ListenKCPOn(pc net.PacketConn) (*kcp.Listener, error)

ListenKCPOn is ListenKCP on pc, which the caller closes.

func ListenQUIC added in v0.35.0

func ListenQUIC(addr string, tlsConfig *tls.Config, quicConfig *quic.Config) (*quic.Listener, error)

ListenQUIC opens the QUIC listener of the bridge on addr.

func NewKCPSessionWithConn added in v0.34.6

func NewKCPSessionWithConn(raddr *net.UDPAddr, pc net.PacketConn) (*kcp.UDPSession, error)

NewKCPSessionWithConn creates a KCP session based on an existing PacketConn.

func NewUdpConnByAddr added in v0.30.4

func NewUdpConnByAddr(addr string) (net.PacketConn, error)

func NewVirtualListener added in v0.30.6

func NewVirtualListener(addr net.Addr) *netx.ChanListener

NewVirtualListener returns an in-memory listener that reports addr, or LocalTCPAddr when addr is nil.

func NewWSListener added in v0.27.0

func NewWSListener(base net.Listener, path, trustedIps, realIpHeader string, route *WSRoute) net.Listener

NewWSListener serves WebSocket bridge connections on path over base. The client address is taken from realIpHeader as written by the proxies in trustedIps; see wsResolver. route, when set, shares the listener.

func NewWSSListener added in v0.27.0

func NewWSSListener(base net.Listener, path string, cert tls.Certificate, trustedIps, realIpHeader string, route *WSRoute) net.Listener

NewWSSListener is NewWSListener over TLS with cert.

func ParseTCPAddr added in v0.34.8

func ParseTCPAddr(s string) (net.Addr, error)

ParseTCPAddr resolves s, a host:port address. An empty s yields a nil address and no error.

func ProxyProtocolHeader added in v0.34.8

func ProxyProtocolHeader(version int, client, target net.Addr) *proxyproto.Header

ProxyProtocolHeader returns the PROXY protocol header of version 1 or 2 for a connection from client to target, or nil for any other version. The addresses are taken as proxyproto.NewHeader takes them: an unknown or unspecified target becomes the zero address of the client's family, and an IPv4 and an IPv6 address are both sent as IPv6. A pair that it rejects, such as a nil client, an address without an IP or addresses of other types, gives a header without addresses ("PROXY UNKNOWN" for version 1, a PROXY command of the AF_UNSPEC family for version 2), so that the backend uses the connection's own addresses.

func ServeKCP added in v0.35.0

func ServeKCP(l *kcp.Listener, f func(c net.Conn)) error

ServeKCP hands every session l accepts to f. It returns once l fails or is closed, and closes l.

func ServeVirtual added in v0.34.8

func ServeVirtual(l *netx.ChanListener, c net.Conn)

ServeVirtual hands c to l, closing c if l is closed or its queue is full.

func SetUdpSession

func SetUdpSession(sess *kcp.UDPSession)

SetUdpSession udp connection setting

func SignalStream added in v0.35.0

func SignalStream(c net.Conn) net.Conn

SignalStream makes a stream opened for a signal connection end its whole connection when it closes, as a signal connection's end means the end of the connection; other streams are returned as they are.

func SourceGone added in v0.35.0

func SourceGone(c net.Conn) bool

SourceGone reports whether the peer of c has closed it, looking at the socket under c without taking anything from it, so that it can be asked while the connection is still to be relayed. Data waiting to be read means the peer is there. It is false where the question cannot be answered: a connection without a socket, or a platform without peekSocketClosed.

Types

type ClientSession added in v0.35.0

type ClientSession interface {
	// OpenLink opens a connection to link's target through the client. taskID
	// is the task the link is for, 0 if it is for none.
	OpenLink(link *Link, taskID int) (net.Conn, error)
}

ClientSession is how the server's proxies reach a client: they open links on it, whatever protocol carries them.

type Conn

type Conn struct {
	Conn net.Conn
	// contains filtered or unexported fields
}

func NewConn

func NewConn(conn net.Conn) *Conn

NewConn new conn

func (*Conn) BufferWrite added in v0.29.38

func (s *Conn) BufferWrite(b []byte) (int, error)

func (*Conn) Close

func (s *Conn) Close() error

func (*Conn) FlushBuf added in v0.29.38

func (s *Conn) FlushBuf() error

func (*Conn) IsClosed added in v0.30.3

func (s *Conn) IsClosed() bool

func (*Conn) LocalAddr

func (s *Conn) LocalAddr() net.Addr

func (*Conn) OnClose added in v0.32.0

func (s *Conn) OnClose(fn func(*Conn)) *Conn

func (*Conn) Read

func (s *Conn) Read(b []byte) (n int, err error)

Read reads into b from the connection.

func (*Conn) RemoteAddr

func (s *Conn) RemoteAddr() net.Addr

func (*Conn) SetAlive

func (s *Conn) SetAlive()

SetAlive clears the read deadline.

func (*Conn) SetDeadline

func (s *Conn) SetDeadline(t time.Time) error

func (*Conn) SetReadDeadline

func (s *Conn) SetReadDeadline(t time.Time) error

func (*Conn) SetReadTimeout added in v0.35.0

func (s *Conn) SetReadTimeout(d time.Duration)

SetReadTimeout makes reads fail once d has passed from now.

func (*Conn) SetWriteDeadline

func (s *Conn) SetWriteDeadline(t time.Time) error

func (*Conn) Write

func (s *Conn) Write(b []byte) (n int, err error)

Write writes b to the connection.

type Entry added in v0.35.0

type Entry interface {
	// RelayTarget names where the entry forwards to, for logs.
	RelayTarget() string
	// SetIsHTTP records whether the entry's traffic looks like HTTP.
	SetIsHTTP(bool)
	// RateLimiter returns the entry's limiter, nil if it has none.
	RateLimiter() *rate.Directional
}

Entry is the task or host a relay serves.

type Flow added in v0.35.0

type Flow interface {
	Budget() *byterate.Budget
	Traffic() *byterate.Counter
	// Over reports whether the account is over its traffic and time limits.
	Over() (traffic, expired bool)
}

Flow is a traffic account that connections count in and charge to. All its methods take a nil receiver of the implementing type, which accounts nothing.

type FlowConn added in v0.28.3

type FlowConn struct {
	net.Conn
	// contains filtered or unexported fields
}

FlowConn counts the payload of a connection in the flows of its task and client and charges it to their budgets: reads count as outbound and writes as inbound traffic. A write never takes a flow past its traffic limit, a read or write past a limit fails with an error naming the flow, and the connection is closed once a flow's time limit passes.

func NewFlowConn added in v0.28.3

func NewFlowConn(conn io.ReadWriteCloser, task, client Flow) *FlowConn

NewFlowConn wraps conn for the flows task and client, either of which may be nil. The addresses and deadlines are those of the connection beneath.

func (*FlowConn) Close added in v0.35.0

func (c *FlowConn) Close() error

Close closes the connection and stops waiting for the time limits.

func (*FlowConn) Read added in v0.28.3

func (c *FlowConn) Read(p []byte) (int, error)

func (*FlowConn) Write added in v0.28.3

func (c *FlowConn) Write(p []byte) (int, error)
type Link struct {
	ConnType string //连接类型
	Host     string //目标
	// Crypt and Compress are what the opener still applies to the connection
	// OpenLink returned: a protocol that encrypts or compresses a link
	// itself clears them.
	Crypt      bool //加密
	Compress   bool
	LocalProxy bool
	RemoteAddr string
	Option     Options
}
func NewLink(connType string, host string, crypt bool, compress bool, remoteAddr string, localProxy bool, opts ...Option) *Link

type Option

type Option func(*Options)

type Options

type Options struct {
	Timeout time.Duration
	NeedAck bool
	// Node is the UUID of the node to open the link through, chosen by the
	// server; empty leaves the choice to the client's select mode.
	Node string `json:"-"`
	// Compress is the compression of a link carried by the core protocol,
	// algorithms in order of preference; the old protocol uses Link.Compress.
	Compress []string `json:"-"`
	// Gone reports that the connection this link is for went away, so that
	// a wait for the client need not last; nil is never.
	Gone func() bool `json:"-"`
}

type QuicAutoCloseConn added in v0.30.4

type QuicAutoCloseConn struct {
	*QuicStreamConn
	// contains filtered or unexported fields
}

func NewQuicAutoCloseConn added in v0.30.4

func NewQuicAutoCloseConn(stream *quic.Stream, sess *quic.Conn) *QuicAutoCloseConn

func (*QuicAutoCloseConn) Close added in v0.30.4

func (q *QuicAutoCloseConn) Close() error

Close closes the stream and, unless the peer closes the connection first, the connection after quicCloseDrain. Closing the connection right away would discard stream data the peer has not acknowledged yet.

type QuicCarrier added in v0.35.0

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

QuicCarrier makes a QUIC connection a carrier of streams, so that nothing but this file has to know about QUIC to use it.

func CarrierOf added in v0.35.0

func CarrierOf(c net.Conn) (*QuicCarrier, bool)

CarrierOf returns the carrier of a connection whose first stream is c, if c is a QUIC stream.

func NewQuicCarrier added in v0.35.0

func NewQuicCarrier(sess *quic.Conn) *QuicCarrier

NewQuicCarrier returns the carrier of sess.

func (*QuicCarrier) AcceptStream added in v0.35.0

func (q *QuicCarrier) AcceptStream(ctx context.Context) (net.Conn, error)

AcceptStream returns the next stream the peer opened.

func (*QuicCarrier) Close added in v0.35.0

func (q *QuicCarrier) Close() error

Close closes the connection and its streams.

func (*QuicCarrier) Closed added in v0.35.0

func (q *QuicCarrier) Closed() bool

Closed reports whether the connection has closed.

func (*QuicCarrier) OpenStream added in v0.35.0

func (q *QuicCarrier) OpenStream(ctx context.Context) (net.Conn, error)

OpenStream opens a stream on the connection.

func (*QuicCarrier) Reason added in v0.35.0

func (q *QuicCarrier) Reason() string

Reason says why the connection closed.

type QuicStreamConn added in v0.30.4

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

func NewQuicStreamConn added in v0.30.4

func NewQuicStreamConn(stream *quic.Stream, sess *quic.Conn) *QuicStreamConn

func (*QuicStreamConn) Close added in v0.30.4

func (q *QuicStreamConn) Close() error

func (*QuicStreamConn) GetSession added in v0.31.0

func (q *QuicStreamConn) GetSession() *quic.Conn

func (*QuicStreamConn) LocalAddr added in v0.30.4

func (q *QuicStreamConn) LocalAddr() net.Addr

func (*QuicStreamConn) Read added in v0.30.4

func (q *QuicStreamConn) Read(p []byte) (int, error)

func (*QuicStreamConn) RemoteAddr added in v0.30.4

func (q *QuicStreamConn) RemoteAddr() net.Addr

func (*QuicStreamConn) SetDeadline added in v0.30.4

func (q *QuicStreamConn) SetDeadline(t time.Time) error

func (*QuicStreamConn) SetReadDeadline added in v0.30.4

func (q *QuicStreamConn) SetReadDeadline(t time.Time) error

func (*QuicStreamConn) SetWriteDeadline added in v0.30.4

func (q *QuicStreamConn) SetWriteDeadline(t time.Time) error

func (*QuicStreamConn) Write added in v0.30.4

func (q *QuicStreamConn) Write(p []byte) (int, error)

type SmartUdpConn added in v0.30.4

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

func NewSmartUdpConn added in v0.30.4

func NewSmartUdpConn(conns []net.PacketConn, addr *net.UDPAddr) *SmartUdpConn

func (*SmartUdpConn) Close added in v0.30.4

func (s *SmartUdpConn) Close() error

func (*SmartUdpConn) LocalAddr added in v0.30.4

func (s *SmartUdpConn) LocalAddr() net.Addr

func (*SmartUdpConn) ReadFrom added in v0.30.4

func (s *SmartUdpConn) ReadFrom(p []byte) (int, net.Addr, error)

func (*SmartUdpConn) SetDeadline added in v0.30.4

func (s *SmartUdpConn) SetDeadline(t time.Time) error

func (*SmartUdpConn) SetReadDeadline added in v0.30.4

func (s *SmartUdpConn) SetReadDeadline(t time.Time) error

func (*SmartUdpConn) SetWriteDeadline added in v0.30.4

func (s *SmartUdpConn) SetWriteDeadline(t time.Time) error

func (*SmartUdpConn) UDPConns added in v0.34.8

func (s *SmartUdpConn) UDPConns() []*net.UDPConn

func (*SmartUdpConn) WriteTo added in v0.30.4

func (s *SmartUdpConn) WriteTo(p []byte, addr net.Addr) (int, error)

type SnappyConn

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

func NewSnappyConn

func NewSnappyConn(conn io.ReadWriteCloser) *SnappyConn

func (*SnappyConn) Close

func (s *SnappyConn) Close() error

func (*SnappyConn) Read

func (s *SnappyConn) Read(b []byte) (n int, err error)

Read reads and decompresses snappy data into b.

func (*SnappyConn) Write

func (s *SnappyConn) Write(b []byte) (n int, err error)

Write compresses b with snappy and writes it.

type TLSStateConn added in v0.35.0

type TLSStateConn struct {
	net.Conn
	State *tls.ConnectionState
}

TLSStateConn is a connection whose TLS this process already terminated, as a replayed view that net/http cannot see through.

type UDP5Policy added in v0.35.0

type UDP5Policy func(addr string, ips []netip.Addr) bool

UDP5Policy decides the destination of a datagram, addr being host:port. It is called with ips nil for a name not yet resolved, where it refuses what the name alone refuses, and again with the addresses the name resolved to; an IP destination comes with itself as ips.

type UDPSplit added in v0.35.0

type UDPSplit struct {
	KCP, QUIC *splitSide
	// contains filtered or unexported fields
}

UDPSplit shares one UDP socket between KCP (FEC 10/3 without encryption, as ListenKCP) and QUIC. The first packet of a source tells which: a KCP packet has the FEC type f1 or f2 at bytes 4 and 5, a QUIC long header does not (its bytes 1 to 4 are the version). The source is remembered until it has been silent for splitIdle. Both sides see plain net.PacketConns, so QUIC runs without GSO and batched reads here.

func ListenUDPSplit added in v0.35.0

func ListenUDPSplit(addr string) (*UDPSplit, error)

ListenUDPSplit listens on addr and starts splitting; Close ends it.

func (*UDPSplit) Close added in v0.35.0

func (s *UDPSplit) Close() error

Close closes the socket and both sides; the read loop has ended when the sides report errors.

type WSRoute added in v0.35.0

type WSRoute struct {
	// Wrap wraps the handler of the bridge path.
	Wrap func(http.Handler) http.Handler
	// Paths are further paths and their handlers. A path that is also the
	// bridge path replaces it.
	Paths map[string]http.Handler
	// NotFound serves the paths nothing else takes; nil is the mux's 404.
	NotFound http.Handler
}

WSRoute is how another protocol shares a WebSocket bridge listener. Both fields are optional.

Jump to

Keyboard shortcuts

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