peer

package
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: AGPL-3.0 Imports: 13 Imported by: 0 modules, 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

Overview

Package peer is the session layer every RemoHop feature is built on.

A Conn is one authenticated, end-to-end encrypted P2P session between a controlling client and a controlled host. It multiplexes independent bidirectional streams; every stream starts with a small JSON header naming the service it is for, so each feature (shell, fs, forward, ...) owns its own wire protocol on its own streams and never has to coordinate with the others.

Establishing the session (rendezvous, UDP hole punching, the password handshake) is not this package's job: internal/dial and internal/hostd do that and hand a ready Mux to NewConn (or to New, then Start once the session is set up).

Index

Constants

View Source
const (
	DatagramForwardUDP byte = 0x01
	DatagramVPN        byte = 0x02
	DatagramMesh       byte = 0x03 // internal/mesh
	DatagramDesktop    byte = 0x04 // internal/svc/desktop: real-time video
)

Tags in use. A service picks one constant and uses it on both ends.

View Source
const ALPN = "remohop/1"

ALPN is the application protocol negotiated on every RemoHop P2P session.

View Source
const DatagramOverhead = 1

DatagramOverhead is the number of bytes Send adds to a payload.

View Source
const ErrUnknownService = "unknown service"

ErrUnknownService is the message a peer answers with when nothing is registered under the requested name.

View Source
const IdleTimeout = 20 * time.Second

IdleTimeout ends a P2P session that has received nothing for this long; see QUICConfig.

View Source
const MaxStreams = 1024

MaxStreams bounds how many streams the peer may have open towards us at once. It is enforced before login, and QUIC makes the receiver create state for every stream ID up to the highest one used, so it has to be small: a stranger costs at most this many stream objects per connection. A thousand is still far more concurrent forwarded connections than anyone needs.

Variables

View Source
var ErrNoDatagrams = errors.New("peer: session does not support datagrams")

ErrNoDatagrams is returned when the session cannot carry datagrams (it does not run directly on QUIC, or the peer did not enable them). Callers fall back to a stream.

View Source
var HostServices = NewRegistry()

HostServices is the registry of services a host exposes to authenticated clients. Service packages add themselves from init().

Functions

func ClosedByPeer

func ClosedByPeer(c *Conn) (reason string, ok bool)

ClosedByPeer is the reason the other side gave (Conn.CloseWithReason) when it ended the session; ok is false while the session lasts and when it ended any other way (closed here, timed out, a network error).

func DatagramTooLarge

func DatagramTooLarge(err error) (max int, ok bool)

DatagramTooLarge reports whether err, from Send, says the datagram did not fit the path, and if so the largest payload Send takes now. That limit follows the path's MTU, which QUIC discovers as the session runs: it can grow, and it is smaller again on a path that cannot carry it.

func DecodeReq

func DecodeReq(req json.RawMessage, v any) error

DecodeReq unmarshals a handler's req into v, treating an absent request as the zero value.

func Handle

func Handle(name string, h Handler)

Handle registers a host service in HostServices.

func QUICConfig

func QUICConfig() *quic.Config

QUICConfig returns the QUIC parameters used for P2P sessions. Keep-alives hold the NAT mappings open; the generous flow-control windows let file transfer and video use the whole path.

The idle timeout decides how long a peer that vanished (killed, unplugged, lid closed) goes unnoticed: a frozen picture for the viewer, capture and encoding running on for nobody on the host. It runs from the last packet received or, after that, the first keep-alive sent, so a vanished peer is noticed about 20 to 28 s later (25 s measured; it was 52 s with 45 s and 10 s). 20 s with a keep-alive after 8 s of silence leaves room for two keep-alives, each retransmitted within a round trip or two if lost, so a lossy but working path is not taken for a dead one; and a phone's radio is woken little more often than with the 10 s keep-alive before. Peers negotiate the smaller of their two idle timeouts, and older peers send keep-alives every 10 s, inside it.

func QUICConn

func QUICConn(c *Conn) *quic.Conn

QUICConn returns the QUIC connection underneath c, or nil if c does not run directly on QUIC. It is for features that need datagrams or path stats.

Types

type Conn

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

Conn is one authenticated session with a remote peer.

func New

func New(m Mux, opts Options) *Conn

New wraps an already authenticated mux without serving anything yet. Streams the remote side opens wait (in the transport's flow control) until Start, so a host can attach everything its services rely on (SetValue: the session, its grant guard) and admit the session before the first of them is handled. The caller must call Start or Close.

func NewConn

func NewConn(m Mux, opts Options) *Conn

NewConn wraps an already authenticated mux and starts serving inbound streams: New followed by Start. Use it where nothing about the session has to be in place before the remote side's first stream is served.

func (*Conn) Close

func (c *Conn) Close() error

Close ends the session and every stream on it.

func (*Conn) CloseWithReason

func (c *Conn) CloseWithReason(reason string) error

CloseWithReason ends the session, reporting reason to the peer.

func (*Conn) Context

func (c *Conn) Context() context.Context

Context is cancelled when the session ends.

func (*Conn) Datagrams

func (c *Conn) Datagrams(tag byte) (*DatagramChannel, error)

Datagrams returns the channel for tag, creating it on first use. Every call with the same tag returns the same channel.

func (*Conn) Done

func (c *Conn) Done() <-chan struct{}

Done is closed when the session ends.

func (*Conn) HandleLocal

func (c *Conn) HandleLocal(name string, h Handler)

HandleLocal registers a service the remote side may open on this specific session, on top of Options.Services. It is how a client accepts callbacks from the host it is controlling (for example reverse port forwards).

func (*Conn) LoadOrStoreValue

func (c *Conn) LoadOrStoreValue(key, value any) (actual any, loaded bool)

LoadOrStoreValue returns the existing value for key, or stores and returns value.

func (*Conn) LocalAddr

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

LocalAddr is our network address on the P2P path.

func (*Conn) Open

func (c *Conn) Open(ctx context.Context, service string, req any) (Stream, error)

Open starts a new stream for service on the remote peer. req is marshalled to JSON and delivered to the remote handler; it may be nil. Open returns once the remote side has accepted the stream; after that the stream carries whatever protocol the service defines.

func (*Conn) RemoteAddr

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

RemoteAddr is the peer's network address on the P2P path.

func (*Conn) RemoteID

func (c *Conn) RemoteID() string

RemoteID is the peer's RemoHop ID (or address for direct sessions).

func (*Conn) Role

func (c *Conn) Role() Role

Role reports which end of the session this is.

func (*Conn) SetValue

func (c *Conn) SetValue(key, value any)

SetValue attaches per-session state under key.

func (*Conn) Start

func (c *Conn) Start()

Start begins serving the streams the remote side opens. Calls after the first do nothing.

func (*Conn) Value

func (c *Conn) Value(key any) (any, bool)

Value returns per-session state stored with SetValue.

func (*Conn) WaitHandlers

func (c *Conn) WaitHandlers(timeout time.Duration) bool

WaitHandlers waits, at most timeout, until every handler of a stream the remote side opened has returned, and reports whether they all did. After the session ends, handlers still undo what they set up (a USB device handed back to its driver, say); a host that is shutting down waits for that before the process exits.

type DatagramChannel

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

DatagramChannel is one service's share of the session's datagrams.

func (*DatagramChannel) Receive

func (d *DatagramChannel) Receive(ctx context.Context) ([]byte, error)

Receive returns the next datagram for this channel. The slice is the caller's to keep.

func (*DatagramChannel) Send

func (d *DatagramChannel) Send(p []byte) error

Send transmits one datagram. It fails with *quic.DatagramTooLargeError when p does not fit the path, which is the caller's cue to use a stream instead.

type Handler

type Handler func(ctx context.Context, c *Conn, s Stream, req json.RawMessage) error

Handler serves one inbound stream. req is the service-specific request the opener passed to Conn.Open. The stream is closed when the handler returns; ctx is cancelled when the session ends.

type Mux

type Mux interface {
	OpenStream(ctx context.Context) (Stream, error)
	AcceptStream(ctx context.Context) (Stream, error)
	// Close tears the whole session down.
	Close(reason string) error
	// Context is cancelled when the session ends for any reason.
	Context() context.Context
	LocalAddr() net.Addr
	RemoteAddr() net.Addr
}

Mux is the stream multiplexer a Conn runs on. QUICMux adapts a QUIC connection; other implementations can proxy a session over a local socket.

func QUICClientMux

func QUICClientMux(q *quic.Conn) Mux

QUICClientMux is QUICMux for a client connection that may move to another path while it runs (internal/dial moves a relayed session to a direct path). quic-go replaces a client connection's send path on a switch without synchronising that with LocalAddr and RemoteAddr, so this mux takes both once, now, and keeps answering with them.

func QUICMux

func QUICMux(q *quic.Conn) Mux

QUICMux adapts an established QUIC connection to Mux.

type Options

type Options struct {
	Role Role
	// RemoteID is the peer's RemoHop ID, or its address for direct sessions.
	RemoteID string
	// Services are the services the remote side may open on us. Hosts pass
	// HostServices. Clients normally leave it nil: a host must never be able
	// to open a shell on the machine controlling it. Clients opt in to
	// individual callbacks with Conn.HandleLocal.
	Services *Registry
	// Authorize, when set, is asked before every stream the remote side
	// opens on Services; a non-nil error refuses the stream with that
	// message. It is how a host applies per-feature permissions. Handlers
	// registered with HandleLocal are not subject to it.
	Authorize func(service string) error
	// OnClose, when set, runs once, synchronously, when Close or
	// CloseWithReason ends the session (after the transport is closed),
	// so it is done before the process can exit. A dialler uses it to
	// release a relay session.
	OnClose func()
}

Options configures NewConn.

type Registry

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

Registry is a set of named services.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty registry.

func (*Registry) Handle

func (r *Registry) Handle(name string, h Handler)

Handle registers h under name, replacing any previous handler.

func (*Registry) Names

func (r *Registry) Names() []string

Names lists the registered services, sorted.

func (*Registry) Wrapped

func (r *Registry) Wrapped(wrap func(name string, h Handler) Handler) *Registry

Wrapped returns a registry that serves r's services with each handler passed through wrap when a stream asks for it, so a host can put the same logic around every service (internal/hostd ends a stream whose feature is switched off). Services registered on r later are served too; those registered on the returned registry itself are served as they are and take precedence.

type RemoteError

type RemoteError struct {
	Service string
	Message string
}

RemoteError is returned by Open when the remote side refuses the stream.

func (*RemoteError) Error

func (e *RemoteError) Error() string

type Role

type Role int

Role says which end of the session this process is.

const (
	// RoleClient is the controlling side (the `remohop <ID> ...` CLI, the MCP server).
	RoleClient Role = iota
	// RoleHost is the controlled side (`remohop host`).
	RoleHost
)

func (Role) String

func (r Role) String() string

type Stream

type Stream interface {
	io.Reader
	io.Writer
	// Close ends the stream gracefully: buffered writes are flushed and the
	// peer sees EOF, and our read side is abandoned.
	Close() error
	// CloseWrite half-closes: the peer sees EOF but we can keep reading.
	CloseWrite() error
	// Reset aborts both directions immediately, discarding buffered data.
	Reset()
	// Context is cancelled once our write side is finished: closed or reset
	// by us, or abandoned by the peer. A handler that is not currently
	// reading uses it to notice that the other end has gone away.
	Context() context.Context
	SetDeadline(t time.Time) error
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
}

Stream is one bidirectional, reliable, ordered byte stream inside a Conn.

Directories

Path Synopsis
Package peertest gives service packages a real client<->host session to test against without rendezvous, hole punching or passwords: two QUIC endpoints on loopback wired straight into the session layer.
Package peertest gives service packages a real client<->host session to test against without rendezvous, hole punching or passwords: two QUIC endpoints on loopback wired straight into the session layer.

Jump to

Keyboard shortcuts

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