tenet

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 15 Imported by: 0

README

Tenet

Tenet reverses the direction of TCP-style connections. One program connects to another over a WebSocket, and that program then opens connections back through the WebSocket, as if it could connect directly.

Documentation Latest Version Build Status Code Coverage

Tenet is for a program that can only make outbound connections, such as one in a network that blocks everything inbound, but must still accept connections from outside the network.

Concepts

  • The client is the program that connects out. It connects to the server over a WebSocket, and then accepts the connections that the server opens.
  • The server is the program that the client connects to. It opens connections back to the client through the WebSocket.
  • A tunnel is the WebSocket between a client and a server. Connections pass through it.
  • A connection is a reliable, ordered stream of bytes, like a TCP connection, through a tunnel. The server opens it, and the client accepts it. Many connections share one tunnel.

How it works

  1. The client calls tenet.Connect, which returns a Client and, in the background, sends an HTTP request to a URL that the server serves.
  2. The server's HTTP handler passes the request to tenet.Accept, which upgrades it to a WebSocket and returns a Dialer. The WebSocket starts the tunnel.
  3. The client calls Client.Listen for each network and address that it accepts connections for. Each call returns a Listener, which is a net.Listener.
  4. The server calls Dialer.DialContext with a network and an address. It returns the server's end of a new connection, and Listener.Accept returns the client's end, from the Listener for that network and address.
  5. When the WebSocket ends, every connection through it ends, and the Dialer stops working. The Client connects again, so the tunnel starts again from step 2, with a new Dialer.

Bounds

At most 256 connections wait for Listener.Accept to accept them. A connection beyond that is reset, in the same way as TCP resets a connection beyond its backlog, and the dial for it returns an error that wraps syscall.ECONNRESET. Each connection buffers at most 256 KB in each direction. A network is at most 64 bytes, and an address at most 448 bytes.

See the documentation for the API and examples.

Documentation

Overview

Package tenet reverses the direction of TCP-style connections.

One program connects to another over a WebSocket. That program then opens connections back through the WebSocket, as if it could connect directly.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AcceptOption

type AcceptOption interface {
	// contains filtered or unexported methods
}

An AcceptOption is an option that Accept takes.

If the same option is given more than once, the last one applies.

type Client

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

A Client keeps a tunnel open to a server, so that the server can open connections back to the client via the tunnel.

Obtain a Client by calling Connect. A Client may be used until Client.Close is called.

func Connect

func Connect(url string, options ...ConnectOption) (*Client, error)

Connect returns a Client that connects to the server at the given URL.

The server must pass each request for url to Accept. Connect returns an error if url isn't a valid URL with the scheme "ws" or "wss".

Connect returns immediately, and the Client connects in the background. Whenever the tunnel ends, or an attempt to connect fails, the Client waits, and then connects again.

Each attempt to connect is an HTTP request, made with the http.Client that WithHTTPClient sets, or http.DefaultClient by default.

Example
package main

import (
	"net/http"

	"github.com/dogmatiq/tenet"
)

func main() {
	c, err := tenet.Connect("wss://example.com/tunnel")
	if err != nil {
		panic(err)
	}
	defer c.Close()

	l, err := c.Listen("tcp", "api.internal:443")
	if err != nil {
		panic(err)
	}

	// Serve the Listener in the same way as any other net.Listener.
	if err := http.Serve(l, http.DefaultServeMux); err != nil {
		panic(err)
	}
}

func (*Client) Close

func (c *Client) Close() error

Close stops the Client from connecting again, and closes each of its Listener values. Connections that are already open stay open until they are closed, and the tunnel ends after the last one closes.

Close may be called more than once, and always returns nil.

func (*Client) Listen

func (c *Client) Listen(network, address string) (*Listener, error)

Listen returns a Listener for network and address. Each connection that the server opens with Dialer.DialContext for exactly the same network and address goes to that Listener.

network and address may be any strings, such as "tcp" and "api.internal:443". network is limited to 64 bytes, and address to 448 bytes.

The Listener may be used until Listener.Close or Client.Close is called.

Listen returns an error that wraps syscall.EADDRINUSE if the Client already has an open Listener for the same network and address, as a TCP listen on a port that is already in use does. It returns an error that wraps syscall.EINVAL if network or address is too long. It returns net.ErrClosed once Client.Close has been called.

type ClientObserver

type ClientObserver interface {
	// TunnelOpened is called each time a tunnel opens.
	TunnelOpened()

	// TunnelEnded is called each time a tunnel ends, with why it ended. It is
	// called exactly once for each call to [ClientObserver.TunnelOpened].
	//
	// err wraps [net.ErrClosed] if [Client.Close] ended the tunnel.
	TunnelEnded(err error)

	// TunnelFailed is called each time an attempt to open a tunnel fails, with why
	// it failed.
	TunnelFailed(err error)
}

A ClientObserver learns about each tunnel that a Client opens, and about each attempt to open one that fails.

Pass a ClientObserver to Connect with WithClientObserver.

The Client calls the methods one at a time, in the order that the events happen. A method that blocks delays the Client's next attempt to connect. If the same ClientObserver is given to more than one Client, the calls for different Client values may run at the same time, so it must be safe for concurrent use.

type ConnectOption

type ConnectOption interface {
	// contains filtered or unexported methods
}

A ConnectOption is an option that Connect takes.

If the same option is given more than once, the last one applies.

func WithBackoff

func WithBackoff(f func(n int, err error) time.Duration) ConnectOption

WithBackoff returns a ConnectOption that sets the Client's backoff policy, which decides how long the Client waits before it connects again.

The policy is the function f. The Client calls f each time a tunnel ends, and each time an attempt to connect fails, with why in err. It waits for the duration that f returns, and then connects again. If that duration is zero or less, it connects again immediately. n counts the calls to f since a tunnel was last opened, starting at 1.

By default, the Client waits 1 second, doubles the wait after each call up to 1 minute, and adds random jitter to each wait.

It panics if f is nil.

func WithClientObserver

func WithClientObserver(o ClientObserver) ConnectOption

WithClientObserver returns a ConnectOption that sets the ClientObserver that learns about the tunnels that the Client opens. By default, the Client has no ClientObserver.

It panics if o is nil.

func WithHTTPClient

func WithHTTPClient(c *http.Client) ConnectOption

WithHTTPClient returns a ConnectOption that sets the http.Client that makes each attempt to connect. The client's redirect, proxy and TLS settings apply to each attempt as they do to any other request. The default is http.DefaultClient.

It panics if c is nil.

func WithHeader

func WithHeader(h http.Header) ConnectOption

WithHeader returns a ConnectOption that sets the HTTP headers that each attempt to connect sends, in addition to the headers that the http.Client and the upgrade to a WebSocket add. It copies h, so later changes to h don't affect the Client. It can't replace the headers that the upgrade needs.

A value that changes between attempts, such as a token, belongs in the http.Client that WithHTTPClient sets.

type Dialer

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

A Dialer is the server's half of a tunnel to a Client.

Obtain a Dialer by calling Accept within an HTTP handler that is serving a request initiated by Connect.

func Accept

func Accept(
	w http.ResponseWriter,
	r *http.Request,
	options ...AcceptOption,
) (*Dialer, error)

Accept upgrades r to a WebSocket, and returns a Dialer that opens connections back to the Client that sent r, through the WebSocket.

It is intended to be used within an http.Handler that is serving a request initiated by Connect.

If the upgrade fails, for example because the Client that sent r uses a different version of the tunneling wire format, it writes an HTTP error response to w, and returns an error.

The returned Dialer is not tied to the lifetime of the HTTP handler. It may be used until the tunnel ends.

Example
package main

import (
	"net/http"

	"github.com/dogmatiq/tenet"
)

func main() {
	http.HandleFunc("/tunnel", func(w http.ResponseWriter, r *http.Request) {
		d, err := tenet.Accept(w, r)
		if err != nil {
			return
		}

		conn, err := d.DialContext(r.Context(), "tcp", "api.internal:443")
		if err != nil {
			return
		}
		defer conn.Close()
	})
}

func (*Dialer) Close

func (d *Dialer) Close() error

Close ends the tunnel and every connection through it.

Close may be called more than once. If the tunnel has already ended, Close does nothing. Close always returns nil. It returns an error only so that a Dialer is an io.Closer.

func (*Dialer) DialContext

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

DialContext opens a connection to the client's Listener over the tunnel.

The network and address are used to route the connection to the listener with the same network and address, as created by Client.Listen. If the client has no such Listener, DialContext returns an error that wraps syscall.ECONNREFUSED. It returns an error that wraps syscall.ECONNRESET if that Listener already has too many connections waiting to be accepted. It returns an error that wraps syscall.EINVAL if network is longer than 64 bytes or address is longer than 448 bytes.

The connection's net.Conn.RemoteAddr method returns an address matching the given network and address. Its net.Conn.LocalAddr method returns an address with the same network, whose string form is empty.

DialContext has the same signature as net.Dialer.DialContext, so it can be used wherever a dial function is needed, such as http.Transport.DialContext.

func (*Dialer) Done

func (d *Dialer) Done() <-chan struct{}

Done returns a channel that is closed when the tunnel ends. By then, every connection through the tunnel has ended, and calls to Dialer.DialContext fail.

func (*Dialer) Err

func (d *Dialer) Err() error

Err returns nil until the channel that Dialer.Done returns is closed. Then it returns why the tunnel ended. It returns net.ErrClosed if Dialer.Close ended it.

type Listener

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

A Listener is a net.Listener for the connections that the server opens with Dialer.DialContext for one network and address.

Obtain a Listener by calling Client.Listen. A Listener may be used until Listener.Close or Client.Close is called.

func (*Listener) Accept

func (l *Listener) Accept() (net.Conn, error)

Accept waits for the next connection that the server opens to the Listener's network and address, and returns the Listener's end of it.

It returns net.ErrClosed once Listener.Close or Client.Close is called. It returns no other error, so a function such as http.Server.Serve that serves the Listener keeps serving it while the Client connects again.

The connection's net.Conn.LocalAddr method returns the address that Listener.Addr returns. Its net.Conn.RemoteAddr method returns an address with the same network, whose string form is empty.

func (*Listener) Addr

func (l *Listener) Addr() net.Addr

Addr returns the Listener's address. Its net.Addr.Network and net.Addr.String methods return the network and address that were given to Client.Listen.

func (*Listener) Close

func (l *Listener) Close() error

Close stops the Listener from accepting connections. Connections that the server has opened, but that Listener.Accept has not returned, are closed. Connections that Listener.Accept has returned stay open until they are closed.

After Close, a call to Dialer.DialContext for the Listener's network and address returns an error that wraps syscall.ECONNREFUSED, and Client.Listen may be called again for that network and address.

Close may be called more than once, and always returns nil.

type Option

type Option interface {
	ConnectOption
	AcceptOption
}

An Option is both a ConnectOption and an AcceptOption, so Connect and Accept both take it.

func WithKeepAliveInterval

func WithKeepAliveInterval(d time.Duration) Option

WithKeepAliveInterval returns an Option that sets how often one end of a tunnel checks that the other end still answers. It applies to the Client if it is given to Connect, and to the Dialer if it is given to Accept. The default is 15 seconds.

It panics if d is not positive.

func WithKeepAliveTimeout

func WithKeepAliveTimeout(d time.Duration) Option

WithKeepAliveTimeout returns an Option that sets how long the other end of a tunnel may take to answer a check, or to accept a write, before the tunnel ends. The default is 10 seconds.

It panics if d is not positive.

Jump to

Keyboard shortcuts

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