websockify

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 38 Imported by: 0

README

caddy-websockify

Caddy plugin which proxies WebSocket connections to TCP or Unix sockets, like websockify.

  • Proxies binary WebSocket messages to and from a TCP or Unix socket upstream, with optional TLS (compatible with novnc/websockify).
  • Works with other Caddy features (including fallthrough for non-websocket requests, handle_errors for websocket error responses, and dynamic placeholders in the upstream addresses).
  • Supports multiple upstreams (round-robin with failover).
  • Connects to the upstream before accepting the websocket.
  • Supports WebSocket over HTTP/1.1, HTTP/2, and HTTP/3.
  • Supports TCP keepalive and client pings.
  • Supports graceful shutdown.
  • Configurable timeouts and buffering.
  • Configurable Origin header restrictions.
Usage
Caddy

Build Caddy with the plugin using xcaddy, or import _ "github.com/pgaskin/caddy-websockify".

xcaddy build --with github.com/pgaskin/caddy-websockify

Then use the websockify directive, which is ordered before reverse_proxy. WebSocket requests are proxied to the configured upstream, and all other requests are passed to the next handler.

websockify [<matcher>] [<upstreams...>] {
	to                 <upstreams...>
	dial_timeout       <duration>
	keepalive          off|<duration>
	ping_interval      off|<duration>
	ping_timeout       <duration>
	idle_timeout       <duration>
	buffer_size        <size>
	origins            <patterns...>
	subprotocols       <names...>
	stream_close_delay <duration>

	tls
	tls_server_name          <name>
	tls_insecure_skip_verify
	tls_trust_pool           <module> ...
	tls_client_auth          <automate_name> | <cert_file> <key_file>
	tls_timeout              <duration>
	tls_except_ports         <ports...>
	tls_curves               <curves...>
	tls_renegotiation        <level>
}
  • upstreams, to are the addresses to connect to, like localhost:5900, tcp6/[::1]:5900, or unix//run/vnc.sock (placeholders are supported) (if there is more than one, they are used in round-robin, trying each one sequentially on failure).
  • dial_timeout is the timeout for connecting to each upstream (if not specified, a default timeout is used).
  • keepalive is the TCP keepalive interval for the upstream connection, or off to disable it (if not specified, a default interval is used).
  • ping_interval is how often to send a WebSocket ping to the client, or off to disable it (if not specified, a default interval is used).
  • ping_timeout is how long to wait for the pong before closing the connection (if not specified, this matches ping_interval).
  • idle_timeout closes the connection if no data is transferred in either direction for the specified duration, excluding pings (if not specified, the idle timeout is disabled).
  • buffer_size is the size of the copy buffer for each direction, which is also the largest message sent to the client (if not specified, a default size is used).
  • origins are the allowed Origin hosts for cross-origin connections, as glob patterns like *.example.com, or https://*.example.com to match the scheme too, or * to allow any origin (same-origin connections and requests without an Origin header are always allowed).
  • subprotocols are the WebSocket subprotocols to negotiate (if not specified, binary is used).
  • stream_close_delay is the grace period to keep connections open after the config is unloaded (for example, on a reload) instead of closing them immediately.
  • tls, tls_* matches the built-in reverse_proxy HTTP transport, and uses TLS for the upstream connection if any are set.
  • tls_server_name is set to the host of the upstream address by default, and must be configured explicitly for unix sockets and addresses without a host unless tls_insecure_skip_verify is set (placeholders are supported).
  • tls_timeout is set to dial_timeout if not specified.

For example, to serve noVNC:

vnc.example.com {
	websockify /websockify localhost:5900
	root * /usr/share/novnc
	file_server
	handle_errors {
		respond "{err.status_code} {err.status_text}"
	}
}

For WebSocket over HTTP/2, Caddy must currently be started with GODEBUG=http2xconnect=1 in the environment. If not set, clients will use HTTP/1.1 for websocket connections.

Standalone

You can run caddy-websockify directly as a standalone binary instead of using a Caddyfile. It is also available as caddy websockify in a Caddy build with the plugin enabled.

# install
go install github.com/pgaskin/caddy-websockify/cmd/caddy-websockify@latest

# proxy WebSocket connections on port 6080 to a VNC server
caddy-websockify --from :6080 --to localhost:5900

# also serve noVNC from the same port
caddy-websockify --from :6080 --to localhost:5900 --root /usr/share/novnc

# serve over HTTPS (with HTTP/2 support) with an automatically issued
# certificate, require a password, and proxy to a Unix socket
GODEBUG=http2xconnect=1 caddy-websockify --from vnc.example.com --to unix//run/vnc.sock --root /usr/share/novnc --basic-auth 'user:password'

# serve over HTTPS (with HTTP/2 support) on localhost with a certificate
# from Caddy's internal CA, and proxy other requests to a web app
GODEBUG=http2xconnect=1 caddy-websockify --from https://localhost:6443 --internal-certs --to localhost:5900 --reverse-proxy localhost:8080

# proxy to an upstream using TLS
caddy-websockify --from :6080 --to vnc.example.com:5900 --tls

# show all options
caddy-websockify --help
Comparison
pgaskin/caddy-websockify hadi77ir/caddy-websockify msquee/go-websockify novnc/websockify
Language Go Go Go Python
Upstream types TCP, Unix TCP, WebSocket TCP TCP, Unix
Upstream TLS support Yes Yes - Yes
Multiple upstreams Round-robin with failover Round-robin - -
Dynamic upstreams Caddyfile placeholders - - Plugins
Upstream TCP keepalive Configurable Configurable Go default System default
Client pings Optional, with a timeout - - Optional, without a timeout
Idle timeout Optional - - -
WebSocket over HTTP/2 and HTTP/3 Yes (if GODEBUG=http2xconnect=1) - - -
Connects to the upstream before accepting the WebSocket Yes (502 on failure) - - -
Sends close frame on shutdown Yes - - -
Origin check Optional - - Optional, exact match only
Handshake subprotocols Configurable Not negotiated binary binary
CLI Yes Yes Yes Yes
CLI: HTTPS Automatic (Caddy) Automatic (Caddy) - Manual
CLI: Static files Yes - - Yes
CLI: Authentication Optional (basic, or Caddyfile) - - Optional (basic, client certificate)

Documentation

Overview

Package websockify implements a Caddy HTTP handler which proxies WebSocket connections to TCP or Unix sockets.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrIdleTimeout = errors.New("idle timeout")
	ErrPingTimeout = errors.New("ping timeout")
)

Functions

func IsWebSocket

func IsWebSocket(r *http.Request) bool

IsWebSocket returns true if r is a WebSocket upgrade request.

Types

type Config

type Config struct {
	// PingInterval is the frequency to ping the client at, or zero to disable.
	PingInterval time.Duration

	// PingTimeout is how long to wait for a pong from the client. If zero,
	// [Config.PingInterval] is used. A ping only times out if nothing was
	// received from the client and no data was waiting to be written to the
	// upstream for the entire duration (since the pong may otherwise be queued
	// behind unread data).
	PingTimeout time.Duration

	// IdleTimeout closes the connection if no data is transferred in either
	// direction for this long, excluding pings, or zero to disable.
	IdleTimeout time.Duration

	// BufferSize is the copy buffer size for each direction, which is also the
	// largest chunk sent to the client in a single message at a time. If zero,
	// a reasonable default is used.
	BufferSize int
}

Config controls Proxy.

type Module

type Module struct {
	// Upstream addresses in Caddy format, like "localhost:5900",
	// "tcp6/[::1]:5900", or "unix//run/vnc.sock". Placeholders are expanded for
	// each request. Multiple addresses are used round-robin across all
	// connections, trying each one once sequentially until one connects or all
	// fail.
	Upstreams []string `json:"upstreams,omitempty"`

	// Timeout for connecting to each upstream. If not specified, a default
	// timeout is used.
	DialTimeout caddy.Duration `json:"dial_timeout,omitempty"`

	// TCP keepalive interval for the upstream connection, or negative to
	// disable it. If not specified, a default interval is used.
	KeepAlive caddy.Duration `json:"keepalive,omitempty"`

	// How often to send WebSocket pings to the downstream client, or negative
	// to disable it. If not specified, a default interval is used.
	PingInterval caddy.Duration `json:"ping_interval,omitempty"`

	// How long to wait for a pong from the downstream client before closing the
	// connection. Defaults to the ping interval. Time spent receiving data from
	// the client or waiting to write it to a slow upstream doesn't count.
	PingTimeout caddy.Duration `json:"ping_timeout,omitempty"`

	// Close the connection if no data is transferred in either direction for
	// the specified duration, excluding pings. If not specified, the idle
	// timeout is disabled.
	IdleTimeout caddy.Duration `json:"idle_timeout,omitempty"`

	// Copy buffer size, for each direction, which is also the largest chunk
	// sent to the client in a single message at a time. If not specified, a
	// default size is used.
	BufferSize int `json:"buffer_size,omitempty"`

	// Allowed Origin header host patterns (path.Match syntax, or
	// "scheme://host" to match the scheme too) for cross-origin connections.
	// Same-origin connections and ones without an Origin header are always
	// allowed. Use "*" to allow any origin.
	Origins []string `json:"origins,omitempty"`

	// Subprotocols to negotiate. If not specified, "binary" is used.
	Subprotocols []string `json:"subprotocols,omitempty"`

	// Grace period to keep connections open after the config is unloaded (e.g.,
	// on reload). If not specified, they're closed immediately.
	StreamCloseDelay caddy.Duration `json:"stream_close_delay,omitempty"`

	// If set, TLS is used for the upstream connections. See
	// [reverseproxy.TLSConfig].
	//
	//  - [reverseproxy.TLSConfig.ServerName] is set to the host of the upstream address by default, and must be configured explicitly for unix sockets and addresses without a host unless [reverseproxy.TLSConfig.InsecureSkipVerify] is set. Placeholders are supported.
	//  - [reverseproxy.TLSConfig.HandshakeTimeout] is set to [Module.DialTimeout] if not specified.
	TLS *reverseproxy.TLSConfig `json:"tls,omitempty"`
	// contains filtered or unexported fields
}

Module proxies binary WebSocket connections to an upstream TCP or unix socket (optionally using TLS), passing non-WebSocket requests to the next handler.

WebSocket requests using an HTTP/2 or HTTP/3 Extended CONNECT are supported in addition to HTTP/1.1 upgrades (but clients currently won't use it in practice).

func (Module) CaddyModule

func (Module) CaddyModule() caddy.ModuleInfo

func (*Module) Cleanup

func (m *Module) Cleanup() error

func (*Module) Provision

func (m *Module) Provision(ctx caddy.Context) error

func (*Module) ServeHTTP

func (m *Module) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error

func (*Module) UnmarshalCaddyfile

func (m *Module) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

func (*Module) Validate

func (m *Module) Validate() error

type Stats

type Stats struct {
	BytesUp   int64 // to server
	BytesDown int64 // to client
}

Stats contains the number of bytes transferred in each direction.

func Proxy

func Proxy(ctx context.Context, ws *websocket.Conn, upstream net.Conn, cfg Config) (Stats, error)

Proxy copies binary messages to and from ws and upstream until either side closes, ctx is cancelled, the client stops responding to pings within the ping timeout (if pings are enabled), or no data is transferred and the idle timeout is reached.

Both connections are closed before returning. Errors from Close on ws and upstream are ignored.

The returned error is nil if either side ended the connection normally, otherwise ErrIdleTimeout, ErrPingTimeout, context.Cause, or the error which caused the connection to end.

Directories

Path Synopsis
cmd
caddy-websockify command
Command caddy-websockify is a Caddy build which runs the websockify command directly.
Command caddy-websockify is a Caddy build which runs the websockify command directly.

Jump to

Keyboard shortcuts

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