service

package
v1.11.2 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2024 License: AGPL-3.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrMTUTooSmall = errors.New("MTU must be at least 1280")

Functions

This section is empty.

Types

type ClientConfig

type ClientConfig struct {
	// Name is the name of the client.
	Name string `json:"name"`

	// Protocol is the protocol used by the client.
	// Valid values include "direct", "socks5", "http", "none", "plain", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm".
	Protocol string `json:"protocol"`

	// Network controls the address family of the resolved IP address
	// when the address is a domain name. It is ignored if the address
	// is an IP address.
	//
	// - "ip": Follow the system default.
	// - "ip4": Resolve to an IPv4 address.
	// - "ip6": Resolve to an IPv6 address.
	//
	// If unspecified, "ip" is used.
	Network string `json:"network"`

	// Endpoint is the address of the remote proxy server, if applicable.
	//
	// Do not use if either TCPAddress or UDPAddress is specified.
	Endpoint conn.Addr `json:"endpoint"`

	// TCPAddress is the TCP address of the remote proxy server, if applicable.
	//
	// Do not use if Endpoint is specified.
	TCPAddress conn.Addr `json:"tcpAddress"`

	// UDPAddress is the UDP address of the remote proxy server, if applicable.
	//
	// Do not use if Endpoint is specified.
	UDPAddress conn.Addr `json:"udpAddress"`

	DialerFwmark       int `json:"dialerFwmark"`
	DialerTrafficClass int `json:"dialerTrafficClass"`

	EnableTCP bool `json:"enableTCP"`
	DialerTFO bool `json:"dialerTFO"`

	// TCPFastOpenFallback enables runtime detection of TCP Fast Open support on the dialer.
	//
	// When enabled, the dialer will connect without TFO if TFO is not available on the system.
	// When disabled, the dialer will abort if TFO cannot be enabled on the socket.
	//
	// Available on all platforms.
	TCPFastOpenFallback bool `json:"tcpFastOpenFallback"`

	// MultipathTCP enables multipath TCP on the client.
	//
	// Unlike Go std, we make MPTCP strictly opt-in.
	// That is, if this field is false, MPTCP will be explicitly disabled.
	// This ensures that if Go std suddenly decides to enable MPTCP by default,
	// existing configurations won't encounter issues due to missing features in the kernel MPTCP stack,
	// such as TCP keepalive (as of Linux 6.5), and failed connect attempts won't always be retried once.
	//
	// Available on platforms supported by Go std's MPTCP implementation.
	MultipathTCP bool `json:"multipathTCP"`

	// AllowSegmentedFixedLengthHeader disables the requirement that
	// the fixed-length header must be read in a single read call.
	//
	// This option is useful when the underlying stream transport
	// does not exhibit typical TCP behavior.
	//
	// Only applicable to Shadowsocks 2022 TCP.
	AllowSegmentedFixedLengthHeader bool `json:"allowSegmentedFixedLengthHeader"`

	EnableUDP bool `json:"enableUDP"`
	MTU       int  `json:"mtu"`

	PSK           []byte   `json:"psk"`
	IPSKs         [][]byte `json:"iPSKs"`
	PaddingPolicy string   `json:"paddingPolicy"`

	// SlidingWindowFilterSize is the size of the sliding window filter.
	//
	// The default value is 256.
	//
	// Only applicable to Shadowsocks 2022 UDP.
	SlidingWindowFilterSize int `json:"slidingWindowFilterSize"`

	UnsafeRequestStreamPrefix  []byte `json:"unsafeRequestStreamPrefix"`
	UnsafeResponseStreamPrefix []byte `json:"unsafeResponseStreamPrefix"`
	// contains filtered or unexported fields
}

ClientConfig stores a client configuration. It may be marshaled as or unmarshaled from JSON.

func (*ClientConfig) Initialize added in v1.6.0

func (cc *ClientConfig) Initialize(listenConfigCache conn.ListenConfigCache, dialerCache conn.DialerCache, logger *zap.Logger) (err error)

Initialize initializes the client configuration.

func (*ClientConfig) TCPClient

func (cc *ClientConfig) TCPClient() (zerocopy.TCPClient, error)

TCPClient creates a zerocopy.TCPClient from the ClientConfig.

func (*ClientConfig) UDPClient

func (cc *ClientConfig) UDPClient() (zerocopy.UDPClient, error)

type Config added in v1.3.0

type Config struct {
	Servers []ServerConfig       `json:"servers"`
	Clients []ClientConfig       `json:"clients"`
	DNS     []dns.ResolverConfig `json:"dns"`
	Router  router.Config        `json:"router"`
	Stats   stats.Config         `json:"stats"`
	API     api.Config           `json:"api"`
}

Config is the main configuration structure. It may be marshaled as or unmarshaled from JSON.

func (*Config) Manager added in v1.5.0

func (sc *Config) Manager(logger *zap.Logger) (*Manager, error)

Manager initializes the service manager.

Initialization order: clients -> DNS -> router -> servers

type ListenerConfig added in v1.8.0

type ListenerConfig struct {
	// Network is the network type.
	// Valid values include "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6".
	Network string `json:"network"`

	// Address is the address to listen on.
	Address string `json:"address"`

	// Fwmark sets the listener's fwmark on Linux, or user cookie on FreeBSD.
	//
	// Available on Linux and FreeBSD.
	Fwmark int `json:"fwmark"`

	// TrafficClass sets the traffic class of the listener.
	//
	// Available on most platforms except Windows.
	TrafficClass int `json:"trafficClass"`

	// ReusePort enables SO_REUSEPORT on the listener.
	//
	// Available on Linux and the BSDs.
	ReusePort bool `json:"reusePort"`
}

ListenerConfig is the shared part of TCP listener and UDP server socket configurations.

type Manager added in v1.5.0

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

Manager manages the services.

func (*Manager) Close added in v1.5.0

func (m *Manager) Close()

Close closes the manager.

func (*Manager) Start added in v1.5.0

func (m *Manager) Start(ctx context.Context) error

Start starts all configured services.

func (*Manager) Stop added in v1.5.0

func (m *Manager) Stop()

Stop stops all running services.

type Relay

type Relay interface {
	// String returns the relay service's name.
	String() string

	// Start starts the relay service.
	Start(ctx context.Context) error

	// Stop stops the relay service.
	Stop() error
}

Relay is a relay service that accepts incoming connections/sessions on a server and dispatches them to a client selected by the router.

func NewUDPTransparentRelay added in v1.4.0

func NewUDPTransparentRelay(
	serverName string,
	serverIndex, mtu, packetBufFrontHeadroom, packetBufRecvSize, packetBufSize int,
	listeners []udpRelayServerConn,
	transparentConnListenConfig conn.ListenConfig,
	collector stats.Collector,
	router *router.Router,
	logger *zap.Logger,
) (Relay, error)

type ServerConfig

type ServerConfig struct {
	// Name is the name of the server.
	Name string `json:"name"`

	// Protocol is the protocol the server uses.
	// Valid values include "direct", "tproxy" (Linux only), "socks5", "http", "none", "plain", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm".
	Protocol string `json:"protocol"`

	// TCPListeners is the list of TCP listeners.
	TCPListeners []TCPListenerConfig `json:"tcpListeners"`

	// UDPListeners is the list of UDP listeners.
	UDPListeners []UDPListenerConfig `json:"udpListeners"`

	// MTU is the MTU of the server's designated network path.
	// The value is used for calculating UDP receive buffer size.
	MTU int `json:"mtu"`

	Listen               string `json:"listen"`
	ListenerFwmark       int    `json:"listenerFwmark"`
	ListenerTrafficClass int    `json:"listenerTrafficClass"`

	EnableTCP                 bool `json:"enableTCP"`
	ListenerTFO               bool `json:"listenerTFO"`
	DisableInitialPayloadWait bool `json:"disableInitialPayloadWait"`

	EnableUDP     bool `json:"enableUDP"`
	NatTimeoutSec int  `json:"natTimeoutSec"`

	UDPBatchMode           string `json:"udpBatchMode"`
	UDPRelayBatchSize      int    `json:"udpRelayBatchSize"`
	UDPServerRecvBatchSize int    `json:"udpServerRecvBatchSize"`
	UDPSendChannelCapacity int    `json:"udpSendChannelCapacity"`

	TunnelRemoteAddress conn.Addr `json:"tunnelRemoteAddress"`
	TunnelUDPTargetOnly bool      `json:"tunnelUDPTargetOnly"`

	// AllowSegmentedFixedLengthHeader disables the requirement that
	// the fixed-length header must be read in a single read call.
	//
	// This option is useful when the underlying stream transport
	// does not exhibit typical TCP behavior.
	//
	// Only applicable to Shadowsocks 2022 TCP.
	AllowSegmentedFixedLengthHeader bool `json:"allowSegmentedFixedLengthHeader"`

	PSK           []byte `json:"psk"`
	UPSKStorePath string `json:"uPSKStorePath"`
	PaddingPolicy string `json:"paddingPolicy"`
	RejectPolicy  string `json:"rejectPolicy"`

	// SlidingWindowFilterSize is the size of the sliding window filter.
	//
	// The default value is 256.
	//
	// Only applicable to Shadowsocks 2022 UDP.
	SlidingWindowFilterSize int `json:"slidingWindowFilterSize"`

	UnsafeFallbackAddress      conn.Addr `json:"unsafeFallbackAddress"`
	UnsafeRequestStreamPrefix  []byte    `json:"unsafeRequestStreamPrefix"`
	UnsafeResponseStreamPrefix []byte    `json:"unsafeResponseStreamPrefix"`
	// contains filtered or unexported fields
}

ServerConfig stores a server configuration. It may be marshaled as or unmarshaled from JSON.

func (*ServerConfig) Initialize added in v1.6.0

func (sc *ServerConfig) Initialize(listenConfigCache conn.ListenConfigCache, collector stats.Collector, router *router.Router, logger *zap.Logger, index int) error

Initialize initializes the server configuration.

func (*ServerConfig) PostInit added in v1.6.0

func (sc *ServerConfig) PostInit(credman *cred.Manager, apiSM *ssm.ServerManager) error

PostInit performs post-initialization tasks.

func (*ServerConfig) TCPRelay

func (sc *ServerConfig) TCPRelay() (*TCPRelay, error)

TCPRelay creates a TCP relay service from the ServerConfig.

func (*ServerConfig) UDPRelay

func (sc *ServerConfig) UDPRelay(maxClientPackerHeadroom zerocopy.Headroom) (Relay, error)

UDPRelay creates a UDP relay service from the ServerConfig.

type TCPListenerConfig added in v1.8.0

type TCPListenerConfig struct {
	// ListenerConfig is the shared part of TCP listener and UDP server socket configurations.
	ListenerConfig

	// FastOpen enables TCP Fast Open on the listener.
	//
	// Available on Linux, macOS, FreeBSD, and Windows.
	FastOpen bool `json:"fastOpen"`

	// FastOpenFallback enables runtime detection of TCP Fast Open support on the listener.
	//
	// When enabled, the listener will start without TFO if TFO is not available on the system.
	// When disabled, the listener will abort if TFO cannot be enabled on the socket.
	//
	// Available on all platforms.
	FastOpenFallback bool `json:"fastOpenFallback"`

	// Multipath enables multipath TCP on the listener.
	//
	// Unlike Go std, we make MPTCP strictly opt-in.
	// That is, if this field is false, MPTCP will be explicitly disabled.
	// This ensures that if Go std suddenly decides to enable MPTCP by default,
	// existing configurations won't encounter issues due to missing features in the kernel MPTCP stack,
	// such as TCP keepalive (as of Linux 6.5), and failed connect attempts won't always be retried once.
	//
	// Available on platforms supported by Go std's MPTCP implementation.
	Multipath bool `json:"multipath"`

	// DisableInitialPayloadWait disables the brief wait for initial payload.
	// Setting it to true is useful when the listener only relays server-speaks-first protocols.
	DisableInitialPayloadWait bool `json:"disableInitialPayloadWait"`

	// InitialPayloadWaitTimeout is the read timeout when waiting for the initial payload.
	//
	// The default value is 250ms.
	InitialPayloadWaitTimeout jsonhelper.Duration `json:"initialPayloadWaitTimeout"`

	// InitialPayloadWaitBufferSize is the read buffer size when waiting for the initial payload.
	//
	// The default value is 1440.
	InitialPayloadWaitBufferSize int `json:"initialPayloadWaitBufferSize"`

	// FastOpenBacklog specifies the maximum number of pending TFO connections on Linux.
	// If the value is 0, Go std's listen(2) backlog is used.
	//
	// On other platforms, a non-negative value is ignored, as they do not have the option to set the TFO backlog.
	//
	// On all platforms, a negative value disables TFO.
	FastOpenBacklog int `json:"fastOpenBacklog"`

	// DeferAcceptSecs sets TCP_DEFER_ACCEPT to the given number of seconds on the listener.
	//
	// Available on Linux.
	DeferAcceptSecs int `json:"deferAcceptSecs"`

	// UserTimeoutMsecs sets TCP_USER_TIMEOUT to the given number of milliseconds on the listener.
	//
	// Available on Linux.
	UserTimeoutMsecs int `json:"userTimeoutMsecs"`
}

TCPListenerConfig is the configuration for a TCP listener.

func (*TCPListenerConfig) Configure added in v1.8.0

func (lnc *TCPListenerConfig) Configure(listenConfigCache conn.ListenConfigCache, transparent, serverNativeInitialPayload bool) (tcpRelayListener, error)

Configure returns a TCP listener configuration.

type TCPRelay

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

TCPRelay is a relay service for TCP traffic.

When started, the relay service accepts incoming TCP connections on the server, and dispatches them to a client selected by the router.

TCPRelay implements the Service interface.

func NewTCPRelay

func NewTCPRelay(
	serverIndex int,
	serverName string,
	listeners []tcpRelayListener,
	server zerocopy.TCPServer,
	connCloser zerocopy.TCPConnCloser,
	fallbackAddress conn.Addr,
	collector stats.Collector,
	router *router.Router,
	logger *zap.Logger,
) *TCPRelay

func (*TCPRelay) Start

func (s *TCPRelay) Start(ctx context.Context) error

Start implements the Service Start method.

func (*TCPRelay) Stop

func (s *TCPRelay) Stop() error

Stop implements the Service Stop method.

func (*TCPRelay) String

func (s *TCPRelay) String() string

String implements the Service String method.

type UDPListenerConfig added in v1.8.0

type UDPListenerConfig struct {
	// ListenerConfig is the shared part of TCP listener and UDP server socket configurations.
	ListenerConfig

	// UDPPerfConfig exposes performance tuning options.
	UDPPerfConfig

	// NATTimeout is the duration after which an inactive NAT mapping expires.
	//
	// The default value is 5 minutes.
	NATTimeout jsonhelper.Duration `json:"natTimeout"`
}

UDPListenerConfig is the configuration for a UDP server socket.

func (*UDPListenerConfig) Configure added in v1.8.0

func (lnc *UDPListenerConfig) Configure(listenConfigCache conn.ListenConfigCache, minNATTimeout time.Duration, transparent bool) (udpRelayServerConn, error)

Configure returns a UDP server socket configuration.

type UDPNATRelay

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

UDPNATRelay is an address-based UDP relay service.

Incoming UDP packets are dispatched to NAT sessions based on the source address and port.

func NewUDPNATRelay

func NewUDPNATRelay(
	serverName string,
	serverIndex, mtu, packetBufFrontHeadroom, packetBufRecvSize, packetBufSize int,
	listeners []udpRelayServerConn,
	server zerocopy.UDPNATServer,
	collector stats.Collector,
	router *router.Router,
	logger *zap.Logger,
) *UDPNATRelay

func (*UDPNATRelay) Start

func (s *UDPNATRelay) Start(ctx context.Context) error

Start implements the Service Start method.

func (*UDPNATRelay) Stop

func (s *UDPNATRelay) Stop() error

Stop implements the Service Stop method.

func (*UDPNATRelay) String

func (s *UDPNATRelay) String() string

String implements the Service String method.

type UDPPerfConfig added in v1.8.0

type UDPPerfConfig struct {
	// BatchMode controls the mode of batch receiving and sending.
	//
	// Available values:
	// - "": Platform default.
	// - "no": Do not receive or send packets in batches.
	// - "sendmmsg": Use recvmmsg(2) and sendmmsg(2) calls. This is the default on Linux and NetBSD.
	BatchMode string `json:"batchMode"`

	// RelayBatchSize is the batch size of recvmmsg(2) and sendmmsg(2) calls in relay sessions.
	//
	// The default value is 256.
	RelayBatchSize int `json:"relayBatchSize"`

	// ServerRecvBatchSize is the batch size of a UDP relay's main receive routine.
	//
	// The default value is 64.
	ServerRecvBatchSize int `json:"serverRecvBatchSize"`

	// SendChannelCapacity is the capacity of a UDP relay session's uplink send channel.
	//
	// The default value is 1024.
	SendChannelCapacity int `json:"sendChannelCapacity"`
}

UDPPerfConfig exposes performance tuning parameters for UDP relays.

func (*UDPPerfConfig) CheckAndApplyDefaults added in v1.8.0

func (c *UDPPerfConfig) CheckAndApplyDefaults() error

CheckAndApplyDefaults checks the validity of the configuration and applies default values.

type UDPSessionRelay

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

UDPSessionRelay is a session-based UDP relay service.

Incoming UDP packets are dispatched to NAT sessions based on the client session ID.

func NewUDPSessionRelay

func NewUDPSessionRelay(
	serverName string,
	serverIndex, mtu, packetBufFrontHeadroom, packetBufRecvSize, packetBufSize int,
	listeners []udpRelayServerConn,
	server zerocopy.UDPSessionServer,
	collector stats.Collector,
	router *router.Router,
	logger *zap.Logger,
) *UDPSessionRelay

func (*UDPSessionRelay) Start

func (s *UDPSessionRelay) Start(ctx context.Context) error

Start implements the Service Start method.

func (*UDPSessionRelay) Stop

func (s *UDPSessionRelay) Stop() error

Stop implements the Service Stop method.

func (*UDPSessionRelay) String

func (s *UDPSessionRelay) String() string

String implements the Service String method.

type UDPTransparentRelay added in v1.4.0

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

UDPTransparentRelay is like UDPNATRelay, but for transparent proxy.

func (*UDPTransparentRelay) Start added in v1.4.0

func (s *UDPTransparentRelay) Start(ctx context.Context) error

Start implements the Relay Start method.

func (*UDPTransparentRelay) Stop added in v1.4.0

func (s *UDPTransparentRelay) Stop() error

Stop implements the Relay Stop method.

func (*UDPTransparentRelay) String added in v1.4.0

func (s *UDPTransparentRelay) String() string

String implements the Relay String method.

Jump to

Keyboard shortcuts

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