server

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package server implements the DNS tunneling server. It provides DNS listener functionality that accepts QUIC connections through DNS queries and forwards traffic to upstream TCP services.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidDNSPort     = errors.New("DNS port must be between 1 and 65535")
	ErrInvalidDomain      = errors.New("domain must not be empty")
	ErrInvalidTargetAddr  = errors.New("target address must not be empty")
	ErrMissingCertificate = errors.New("TLS certificate is required")
	ErrMissingPrivateKey  = errors.New("TLS private key is required")
	ErrServerClosed       = errors.New("server is closed")
	ErrServerNotRunning   = errors.New("server is not running")
	ErrConnectionFailed   = errors.New("connection failed")
	ErrUpstreamFailed     = errors.New("upstream connection failed")
	ErrStreamClosed       = errors.New("stream is closed")
)

Common errors for server configuration

Functions

This section is empty.

Types

type CallbackEvent

type CallbackEvent struct {
	// Type is the type of callback event
	Type CallbackType

	// ConnectionID is the connection identifier (if applicable)
	ConnectionID string

	// StreamID is the stream identifier (if applicable)
	StreamID int64

	// PeerAddr is the peer address (DNS client)
	PeerAddr *net.UDPAddr

	// UpstreamAddr is the upstream address
	UpstreamAddr net.Addr

	// Data is the event data (if applicable)
	Data []byte

	// ByteCount is the number of bytes transferred
	ByteCount int

	// Error is the error (if applicable)
	Error error

	// Context provides additional context
	Context context.Context
}

CallbackEvent represents an event passed to callback handlers

type CallbackHandler

type CallbackHandler func(event *CallbackEvent)

CallbackHandler is a function that handles callback events

type CallbackRegistry

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

CallbackRegistry manages callback registrations

func NewCallbackRegistry

func NewCallbackRegistry() *CallbackRegistry

NewCallbackRegistry creates a new callback registry

func (*CallbackRegistry) HasHandlers

func (r *CallbackRegistry) HasHandlers(callbackType CallbackType) bool

HasHandlers returns true if there are handlers registered for a callback type

func (*CallbackRegistry) Register

func (r *CallbackRegistry) Register(callbackType CallbackType, handler CallbackHandler)

Register registers a handler for a callback type

func (*CallbackRegistry) Trigger

func (r *CallbackRegistry) Trigger(event *CallbackEvent)

Trigger triggers all handlers for a callback event

func (*CallbackRegistry) TriggerAsync

func (r *CallbackRegistry) TriggerAsync(event *CallbackEvent)

TriggerAsync triggers all handlers asynchronously

func (*CallbackRegistry) Unregister

func (r *CallbackRegistry) Unregister(callbackType CallbackType)

Unregister removes all handlers for a callback type

type CallbackType

type CallbackType int

CallbackType identifies the type of callback event

const (
	// CallbackTypeServerStarted is called when the server starts
	CallbackTypeServerStarted CallbackType = iota

	// CallbackTypeServerStopped is called when the server stops
	CallbackTypeServerStopped

	// CallbackTypeConnectionAccepted is called when a new connection is accepted
	CallbackTypeConnectionAccepted

	// CallbackTypeConnectionClosed is called when a connection is closed
	CallbackTypeConnectionClosed

	// CallbackTypeStreamOpened is called when a new stream is opened
	CallbackTypeStreamOpened

	// CallbackTypeStreamClosed is called when a stream is closed
	CallbackTypeStreamClosed

	// CallbackTypeStreamData is called when data is received on a stream
	CallbackTypeStreamData

	// CallbackTypeUpstreamConnected is called when upstream connection is established
	CallbackTypeUpstreamConnected

	// CallbackTypeUpstreamDisconnected is called when upstream connection is closed
	CallbackTypeUpstreamDisconnected

	// CallbackTypeQueryReceived is called when a DNS query is received
	CallbackTypeQueryReceived

	// CallbackTypeResponseSent is called when a DNS response is sent
	CallbackTypeResponseSent

	// CallbackTypeError is called when an error occurs
	CallbackTypeError
)

func (CallbackType) String

func (t CallbackType) String() string

String returns the string representation of the callback type

type Config

type Config struct {
	// DNSListenPort is the UDP port to listen for DNS queries on
	// Default: 53
	DNSListenPort int

	// DNSListenAddr is the address to bind the DNS listener to
	// Default: "0.0.0.0" (all interfaces)
	DNSListenAddr string

	// ListenIPv6 enables IPv6 listening in addition to IPv4
	// Default: false
	ListenIPv6 bool

	// TargetAddress is the address of the upstream TCP service to forward to
	// Example: "127.0.0.1:8080"
	TargetAddress string

	// Domain is the base domain used for DNS tunneling
	// All DNS queries must be for subdomains of this domain
	Domain string

	// CertFile is the path to the TLS certificate file
	CertFile string

	// KeyFile is the path to the TLS private key file
	KeyFile string

	// TLSConfig is an optional pre-configured TLS configuration
	// If provided, CertFile and KeyFile are ignored
	TLSConfig *tls.Config

	// MaxConnections is the maximum number of concurrent QUIC connections
	// Default: 1000
	MaxConnections int

	// MaxStreamsPerConnection is the maximum number of streams per connection
	// Default: 100
	MaxStreamsPerConnection int

	// IdleTimeout is the connection idle timeout
	// Default: 30s
	IdleTimeout time.Duration

	// ReadTimeout is the timeout for reading from upstream TCP connections
	// Default: 30s
	ReadTimeout time.Duration

	// WriteTimeout is the timeout for writing to upstream TCP connections
	// Default: 30s
	WriteTimeout time.Duration

	// UpstreamConnectTimeout is the timeout for connecting to upstream TCP services
	// Default: 10s
	UpstreamConnectTimeout time.Duration

	// BufferSize is the buffer size for data transfer
	// Default: 32KB
	BufferSize int

	// EnableLogging enables debug logging
	// Default: false
	EnableLogging bool
}

Config holds the server configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with sensible defaults

func (*Config) Clone

func (c *Config) Clone() *Config

Clone returns a deep copy of the configuration

func (*Config) GetDNSListenAddress

func (c *Config) GetDNSListenAddress() string

GetDNSListenAddress returns the full DNS listen address

func (*Config) GetDNSListenAddressIPv6

func (c *Config) GetDNSListenAddressIPv6() string

GetDNSListenAddressIPv6 returns the IPv6 DNS listen address

func (*Config) LoadTLSConfig

func (c *Config) LoadTLSConfig() (*tls.Config, error)

LoadTLSConfig loads the TLS configuration from certificate and key files

func (*Config) ParseTargetAddress

func (c *Config) ParseTargetAddress() (*net.TCPAddr, error)

ParseTargetAddress parses the target address from configuration

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid

func (*Config) WithCertificates

func (c *Config) WithCertificates(certFile, keyFile string) *Config

WithCertificates returns a new Config with the given certificate and key files

func (*Config) WithDNSAddr

func (c *Config) WithDNSAddr(addr string) *Config

WithDNSAddr returns a new Config with the given DNS listen address

func (*Config) WithDNSPort

func (c *Config) WithDNSPort(port int) *Config

WithDNSPort returns a new Config with the given DNS port

func (*Config) WithDomain

func (c *Config) WithDomain(domain string) *Config

WithDomain returns a new Config with the given domain

func (*Config) WithIPv6

func (c *Config) WithIPv6(enable bool) *Config

WithIPv6 returns a new Config with IPv6 enabled or disabled

func (*Config) WithMaxConnections

func (c *Config) WithMaxConnections(max int) *Config

WithMaxConnections returns a new Config with the given max connections

func (*Config) WithTLSConfig

func (c *Config) WithTLSConfig(tlsConfig *tls.Config) *Config

WithTLSConfig returns a new Config with the given TLS configuration

func (*Config) WithTarget

func (c *Config) WithTarget(addr string) *Config

WithTarget returns a new Config with the given target address

func (*Config) WithTimeouts

func (c *Config) WithTimeouts(idle, read, write time.Duration) *Config

WithTimeouts returns a new Config with the given timeouts

type Connection

type Connection struct {
	// ID is the unique connection identifier
	ID string

	// PeerAddr is the client's address
	PeerAddr *net.UDPAddr
	// contains filtered or unexported fields
}

Connection represents a QUIC connection from a client

func NewConnection

func NewConnection(id string, peerAddr *net.UDPAddr) *Connection

NewConnection creates a new connection

func (*Connection) DecrementStreams

func (c *Connection) DecrementStreams()

DecrementStreams decrements the stream count

func (*Connection) IncrementStreams

func (c *Connection) IncrementStreams()

IncrementStreams increments the stream count

func (*Connection) LastActivity

func (c *Connection) LastActivity() time.Time

LastActivity returns the last activity time

func (*Connection) SetState

func (c *Connection) SetState(state ConnectionState)

SetState sets the connection state

func (*Connection) State

func (c *Connection) State() ConnectionState

State returns the connection state

func (*Connection) StreamCount

func (c *Connection) StreamCount() int

StreamCount returns the number of streams

func (*Connection) UpdateActivity

func (c *Connection) UpdateActivity()

UpdateActivity updates the last activity time

type ConnectionCallback

type ConnectionCallback struct {
	// OnStreamOpened is called when a stream is opened on this connection
	OnStreamOpened func(streamID int64)

	// OnStreamClosed is called when a stream is closed on this connection
	OnStreamClosed func(streamID int64)

	// OnStreamData is called when data is received on a stream
	OnStreamData func(streamID int64, data []byte)

	// OnConnectionClosed is called when this connection is closed
	OnConnectionClosed func()

	// OnError is called when an error occurs on this connection
	OnError func(err error)
}

ConnectionCallback represents callbacks for a specific connection

type ConnectionCallbackHandler

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

ConnectionCallbackHandler wraps ConnectionCallback for handling

func NewConnectionCallbackHandler

func NewConnectionCallbackHandler(connectionID string, callback *ConnectionCallback) *ConnectionCallbackHandler

NewConnectionCallbackHandler creates a new connection callback handler

func (*ConnectionCallbackHandler) HandleConnectionClosed

func (h *ConnectionCallbackHandler) HandleConnectionClosed()

HandleConnectionClosed handles connection closed events

func (*ConnectionCallbackHandler) HandleError

func (h *ConnectionCallbackHandler) HandleError(err error)

HandleError handles error events

func (*ConnectionCallbackHandler) HandleStreamClosed

func (h *ConnectionCallbackHandler) HandleStreamClosed(streamID int64)

HandleStreamClosed handles stream closed events

func (*ConnectionCallbackHandler) HandleStreamData

func (h *ConnectionCallbackHandler) HandleStreamData(streamID int64, data []byte)

HandleStreamData handles stream data events

func (*ConnectionCallbackHandler) HandleStreamOpened

func (h *ConnectionCallbackHandler) HandleStreamOpened(streamID int64)

HandleStreamOpened handles stream opened events

type ConnectionCallbackRegistry

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

ConnectionCallbackRegistry manages per-connection callbacks

func NewConnectionCallbackRegistry

func NewConnectionCallbackRegistry() *ConnectionCallbackRegistry

NewConnectionCallbackRegistry creates a new connection callback registry

func (*ConnectionCallbackRegistry) Get

Get returns the callback handler for a connection

func (*ConnectionCallbackRegistry) Register

func (r *ConnectionCallbackRegistry) Register(connectionID string, callback *ConnectionCallback)

Register registers callbacks for a connection

func (*ConnectionCallbackRegistry) TriggerConnectionClosed

func (r *ConnectionCallbackRegistry) TriggerConnectionClosed(connectionID string)

TriggerConnectionClosed triggers the connection closed callback

func (*ConnectionCallbackRegistry) TriggerError

func (r *ConnectionCallbackRegistry) TriggerError(connectionID string, err error)

TriggerError triggers the error callback for a connection

func (*ConnectionCallbackRegistry) TriggerStreamClosed

func (r *ConnectionCallbackRegistry) TriggerStreamClosed(connectionID string, streamID int64)

TriggerStreamClosed triggers the stream closed callback for a connection

func (*ConnectionCallbackRegistry) TriggerStreamData

func (r *ConnectionCallbackRegistry) TriggerStreamData(connectionID string, streamID int64, data []byte)

TriggerStreamData triggers the stream data callback for a connection

func (*ConnectionCallbackRegistry) TriggerStreamOpened

func (r *ConnectionCallbackRegistry) TriggerStreamOpened(connectionID string, streamID int64)

TriggerStreamOpened triggers the stream opened callback for a connection

func (*ConnectionCallbackRegistry) Unregister

func (r *ConnectionCallbackRegistry) Unregister(connectionID string)

Unregister removes callbacks for a connection

type ConnectionManager

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

ConnectionManager manages QUIC connections

func NewConnectionManager

func NewConnectionManager(maxConns int) *ConnectionManager

NewConnectionManager creates a new connection manager

func (*ConnectionManager) Add

func (m *ConnectionManager) Add(conn *Connection) error

Add adds a new connection

func (*ConnectionManager) CloseAll

func (m *ConnectionManager) CloseAll()

CloseAll closes all connections

func (*ConnectionManager) Count

func (m *ConnectionManager) Count() int

Count returns the number of connections

func (*ConnectionManager) Get

func (m *ConnectionManager) Get(id string) *Connection

Get returns a connection by ID

func (*ConnectionManager) GetAll

func (m *ConnectionManager) GetAll() []*Connection

GetAll returns all connections

func (*ConnectionManager) Remove

func (m *ConnectionManager) Remove(id string) *Connection

Remove removes a connection

type ConnectionState

type ConnectionState int32

ConnectionState represents the state of a connection

const (
	ConnectionStateActive ConnectionState = iota
	ConnectionStateClosing
	ConnectionStateClosed
)

type IOCopier

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

IOCopier handles bidirectional data copying between a stream and upstream connection

func NewIOCopier

func NewIOCopier(stream *Stream, config *IOCopierConfig) *IOCopier

NewIOCopier creates a new I/O copier for bidirectional data transfer

func (*IOCopier) Done

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

Done returns a channel that's closed when copying is done

func (*IOCopier) Errors

func (c *IOCopier) Errors() <-chan error

Errors returns the error channel

func (*IOCopier) Start

func (c *IOCopier) Start()

Start starts the bidirectional copy

func (*IOCopier) Stats

func (c *IOCopier) Stats() IOCopierStats

Stats returns copier statistics

func (*IOCopier) Stop

func (c *IOCopier) Stop()

Stop stops the I/O copier

func (*IOCopier) Wait

func (c *IOCopier) Wait()

Wait waits for the copier to finish

type IOCopierConfig

type IOCopierConfig struct {
	// BufferSize is the copy buffer size
	BufferSize int

	// FlushInterval is how often to flush pending data
	FlushInterval time.Duration
}

IOCopierConfig holds configuration for the I/O copier

func DefaultIOCopierConfig

func DefaultIOCopierConfig() *IOCopierConfig

DefaultIOCopierConfig returns default copier configuration

type IOCopierStats

type IOCopierStats struct {
	BytesCopiedUp   uint64
	BytesCopiedDown uint64
}

IOCopierStats holds statistics for the I/O copier

type Server

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

Server is the DNS tunneling server. It listens for DNS queries, decodes QUIC packets from them, and forwards traffic to upstream TCP services.

func New

func New(config *Config) (*Server, error)

New creates a new DNS tunneling server with the given configuration

func (*Server) Addr

func (s *Server) Addr() net.Addr

Addr returns the server listen address

func (*Server) Close

func (s *Server) Close() error

Close is an alias for Stop

func (*Server) Config

func (s *Server) Config() *Config

Config returns a copy of the server configuration

func (*Server) Context

func (s *Server) Context() context.Context

Context returns the server context

func (*Server) IsRunning

func (s *Server) IsRunning() bool

IsRunning returns true if the server is running

func (*Server) RegisterCallback

func (s *Server) RegisterCallback(callbackType CallbackType, handler CallbackHandler)

RegisterCallback registers a callback handler

func (*Server) SetCallbacks

func (s *Server) SetCallbacks(callbacks *ServerCallbacks)

SetCallbacks sets all callback handlers from a ServerCallbacks struct

func (*Server) Start

func (s *Server) Start() error

Start starts the server

func (*Server) State

func (s *Server) State() ServerState

State returns the current server state

func (*Server) Stats

func (s *Server) Stats() ServerStats

Stats returns a copy of the server statistics

func (*Server) Stop

func (s *Server) Stop() error

Stop stops the server gracefully

func (*Server) WaitForShutdown

func (s *Server) WaitForShutdown()

WaitForShutdown waits for the server to shut down

type ServerCallbacks

type ServerCallbacks struct {
	// OnServerStarted is called when the server starts
	OnServerStarted func()

	// OnServerStopped is called when the server stops
	OnServerStopped func(error)

	// OnConnectionAccepted is called when a new QUIC connection is accepted
	OnConnectionAccepted func(connectionID string, peerAddr *net.UDPAddr)

	// OnConnectionClosed is called when a QUIC connection is closed
	OnConnectionClosed func(connectionID string)

	// OnStreamOpened is called when a new stream is opened
	OnStreamOpened func(connectionID string, streamID int64)

	// OnStreamClosed is called when a stream is closed
	OnStreamClosed func(connectionID string, streamID int64)

	// OnStreamData is called when data is received on a stream
	OnStreamData func(connectionID string, streamID int64, data []byte)

	// OnUpstreamConnected is called when upstream connection is established
	OnUpstreamConnected func(connectionID string, streamID int64, addr net.Addr)

	// OnUpstreamDisconnected is called when upstream connection is closed
	OnUpstreamDisconnected func(connectionID string, streamID int64)

	// OnQueryReceived is called when a DNS query is received
	OnQueryReceived func(peerAddr *net.UDPAddr, queryLen int)

	// OnResponseSent is called when a DNS response is sent
	OnResponseSent func(peerAddr *net.UDPAddr, responseLen int)

	// OnError is called when an error occurs
	OnError func(err error)
}

ServerCallbacks holds callback functions for server events. This provides a simpler interface than the registry-based approach.

func DefaultServerCallbacks

func DefaultServerCallbacks() *ServerCallbacks

DefaultServerCallbacks returns ServerCallbacks with no-op handlers

func (*ServerCallbacks) ToRegistry

func (c *ServerCallbacks) ToRegistry() *CallbackRegistry

ToRegistry converts ServerCallbacks to a CallbackRegistry

type ServerState

type ServerState int32

ServerState represents the state of the server

const (
	// ServerStateInitial indicates the server is initialized but not started
	ServerStateInitial ServerState = iota

	// ServerStateStarting indicates the server is starting
	ServerStateStarting

	// ServerStateRunning indicates the server is running
	ServerStateRunning

	// ServerStateStopping indicates the server is stopping
	ServerStateStopping

	// ServerStateStopped indicates the server is stopped
	ServerStateStopped
)

func (ServerState) String

func (s ServerState) String() string

String returns the string representation of the server state

type ServerStats

type ServerStats struct {
	// Connection stats
	ConnectionsAccepted uint64
	ConnectionsActive   uint64
	ConnectionsClosed   uint64

	// Stream stats
	StreamsOpened uint64
	StreamsClosed uint64

	// Data stats
	QueriesReceived   uint64
	ResponsesSent     uint64
	BytesFromClients  uint64
	BytesToClients    uint64
	BytesFromUpstream uint64
	BytesToUpstream   uint64

	// Error stats
	Errors uint64

	// Timing
	StartedAt      time.Time
	LastActivityAt time.Time
}

ServerStats holds statistics for the server

type Stream

type Stream struct {
	// ID is the unique stream identifier (QUIC stream ID)
	ID int64

	// ConnectionID is the ID of the parent connection
	ConnectionID string

	// Upstream is the TCP connection to the upstream service
	Upstream *UpstreamConnection
	// contains filtered or unexported fields
}

Stream represents a bidirectional tunnel stream on the server side. It bridges data between the QUIC stream (via DNS) and an upstream TCP connection.

func NewStream

func NewStream(id int64, connectionID string, config *StreamConfig) *Stream

NewStream creates a new server stream

func (*Stream) Activate

func (s *Stream) Activate(upstream *UpstreamConnection) bool

Activate marks the stream as active with an upstream connection

func (*Stream) Age

func (s *Stream) Age() time.Duration

Age returns the age of the stream

func (*Stream) CanPoll

func (s *Stream) CanPoll() bool

CanPoll returns true if the stream can be polled for outgoing data

func (*Stream) Close

func (s *Stream) Close() error

Close closes the stream and associated upstream connection

func (*Stream) CompareAndSwapState

func (s *Stream) CompareAndSwapState(expected, new StreamState) bool

CompareAndSwapState atomically updates state if it matches expected

func (*Stream) Context

func (s *Stream) Context() context.Context

Context returns the stream context

func (*Stream) DequeueIncoming

func (s *Stream) DequeueIncoming() ([]byte, bool)

DequeueIncoming dequeues data received from the client

func (*Stream) DequeueIncomingWait

func (s *Stream) DequeueIncomingWait(ctx context.Context) ([]byte, bool)

DequeueIncomingWait dequeues data with a wait

func (*Stream) DequeueOutgoing

func (s *Stream) DequeueOutgoing() ([]byte, bool)

DequeueOutgoing dequeues data to send to the client

func (*Stream) DequeueOutgoingWait

func (s *Stream) DequeueOutgoingWait(timeout time.Duration) ([]byte, bool)

DequeueOutgoingWait dequeues data with a wait and timeout

func (*Stream) EnqueueIncoming

func (s *Stream) EnqueueIncoming(data []byte) bool

EnqueueIncoming enqueues data received from the client via DNS

func (*Stream) EnqueueOutgoing

func (s *Stream) EnqueueOutgoing(data []byte) bool

EnqueueOutgoing enqueues data to send to the client via DNS

func (*Stream) GetUpstreamAddr

func (s *Stream) GetUpstreamAddr() net.Addr

GetUpstreamAddr returns the upstream address for a stream if available

func (*Stream) HasOutgoingData

func (s *Stream) HasOutgoingData() bool

HasOutgoingData returns true if there is data ready to send

func (*Stream) IdleDuration

func (s *Stream) IdleDuration() time.Duration

IdleDuration returns how long the stream has been idle

func (*Stream) IsActive

func (s *Stream) IsActive() bool

IsActive returns true if the stream is active

func (*Stream) IsClosed

func (s *Stream) IsClosed() bool

IsClosed returns true if the stream is closed (not including draining state)

func (*Stream) IsDraining

func (s *Stream) IsDraining() bool

IsDraining returns true if the stream is draining

func (*Stream) IsDrainingExpired

func (s *Stream) IsDrainingExpired() bool

IsDrainingExpired returns true if the draining timeout has expired

func (*Stream) LastActivity

func (s *Stream) LastActivity() time.Time

LastActivity returns the time of the last activity

func (*Stream) ReadFromUpstream

func (s *Stream) ReadFromUpstream() ([]byte, int, error)

ReadFromUpstream reads data from the upstream TCP connection

func (*Stream) SetOnClose

func (s *Stream) SetOnClose(callback func(*Stream))

SetOnClose sets a callback to be called when the stream is closed

func (*Stream) SetState

func (s *Stream) SetState(state StreamState)

SetState sets the stream state

func (*Stream) StartDraining

func (s *Stream) StartDraining() bool

StartDraining transitions the stream to draining state to allow pending data to be consumed. It closes the upstream connection but keeps the stream available for polling. Returns true if draining was started, false if stream was already closed.

func (*Stream) State

func (s *Stream) State() StreamState

State returns the current stream state

func (*Stream) Stats

func (s *Stream) Stats() StreamStats

Stats returns stream statistics

func (*Stream) WriteToUpstream

func (s *Stream) WriteToUpstream(data []byte) (int, error)

WriteToUpstream writes data to the upstream TCP connection

type StreamConfig

type StreamConfig struct {
	// BufferSize is the size of read/write buffers
	BufferSize int

	// IncomingQueueSize is the size of the incoming data queue
	IncomingQueueSize int

	// OutgoingQueueSize is the size of the outgoing data queue
	OutgoingQueueSize int

	// DrainingTimeout is the maximum time to wait while draining outgoing data
	DrainingTimeout time.Duration
}

StreamConfig holds configuration for stream creation

func DefaultStreamConfig

func DefaultStreamConfig() *StreamConfig

DefaultStreamConfig returns default stream configuration

type StreamManager

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

StreamManager manages multiple server streams

func NewStreamManager

func NewStreamManager(maxStreams int) *StreamManager

NewStreamManager creates a new stream manager

func (*StreamManager) Close

func (m *StreamManager) Close() error

Close closes all streams and the manager

func (*StreamManager) Count

func (m *StreamManager) Count() int

Count returns the number of active streams

func (*StreamManager) CountByConnection

func (m *StreamManager) CountByConnection(connectionID string) int

CountByConnection returns the number of streams for a connection

func (*StreamManager) CreateStream

func (m *StreamManager) CreateStream(connectionID string, config *StreamConfig) (*Stream, error)

CreateStream creates a new stream for a connection

func (*StreamManager) FindIdleStreams

func (m *StreamManager) FindIdleStreams(maxIdle time.Duration) []*Stream

FindIdleStreams returns streams that have been idle longer than the given duration

func (*StreamManager) ForEachStream

func (m *StreamManager) ForEachStream(fn func(*Stream) bool)

ForEachStream calls the given function for each active stream

func (*StreamManager) GetAllStreams

func (m *StreamManager) GetAllStreams() []*Stream

GetAllStreams returns all active streams

func (*StreamManager) GetStream

func (m *StreamManager) GetStream(streamID int64) *Stream

GetStream returns a stream by its ID

func (*StreamManager) GetStreamsByConnection

func (m *StreamManager) GetStreamsByConnection(connectionID string) []*Stream

GetStreamsByConnection returns all streams for a connection

func (*StreamManager) IsClosed

func (m *StreamManager) IsClosed() bool

IsClosed returns true if the manager is closed

func (*StreamManager) RemoveConnectionStreams

func (m *StreamManager) RemoveConnectionStreams(connectionID string)

RemoveConnectionStreams removes all streams for a connection

func (*StreamManager) RemoveStream

func (m *StreamManager) RemoveStream(streamID int64)

RemoveStream removes a stream by its ID

func (*StreamManager) SetOnStreamClosed

func (m *StreamManager) SetOnStreamClosed(callback func(*Stream))

SetOnStreamClosed sets a callback for when streams are closed

func (*StreamManager) Stats

func (m *StreamManager) Stats() StreamManagerStats

Stats returns the stream manager statistics

type StreamManagerStats

type StreamManagerStats struct {
	TotalStreams      uint64
	ActiveStreams     uint64
	ClosedStreams     uint64
	TotalBytesIn      uint64
	TotalBytesOut     uint64
	StreamsByConnSize int
}

StreamManagerStats holds statistics for the stream manager

type StreamState

type StreamState int32

StreamState represents the current state of a server stream

const (
	// StreamStateNew indicates a newly created stream
	StreamStateNew StreamState = iota
	// StreamStateActive indicates an active, tunneling stream
	StreamStateActive
	// StreamStateClosing indicates a stream that is being closed
	StreamStateClosing
	// StreamStateClosed indicates a fully closed stream
	StreamStateClosed
	// StreamStateDraining indicates stream is draining outgoing data before closure
	StreamStateDraining
)

func (StreamState) String

func (s StreamState) String() string

String returns the string representation of the stream state

type StreamStats

type StreamStats struct {
	ID              int64
	ConnectionID    string
	State           StreamState
	CreatedAt       time.Time
	LastActivity    time.Time
	BytesFromClient uint64
	BytesToClient   uint64
}

StreamStats holds statistics for a stream

type UpstreamConfig

type UpstreamConfig struct {
	// TargetAddress is the address to connect to
	TargetAddress string

	// ConnectTimeout is the timeout for establishing the connection
	ConnectTimeout time.Duration

	// ReadTimeout is the timeout for read operations
	ReadTimeout time.Duration

	// WriteTimeout is the timeout for write operations
	WriteTimeout time.Duration

	// KeepAlive enables TCP keep-alive
	KeepAlive bool

	// KeepAliveInterval is the keep-alive probe interval
	KeepAliveInterval time.Duration
}

UpstreamConfig holds configuration for upstream connections

func DefaultUpstreamConfig

func DefaultUpstreamConfig() *UpstreamConfig

DefaultUpstreamConfig returns default upstream configuration

type UpstreamConnection

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

UpstreamConnection represents a TCP connection to an upstream service. It manages the lifecycle and I/O operations for forwarding data.

func NewUpstreamConnection

func NewUpstreamConnection(streamID int64, connectionID string, config *UpstreamConfig) (*UpstreamConnection, error)

NewUpstreamConnection creates a new upstream connection

func (*UpstreamConnection) Close

func (u *UpstreamConnection) Close() error

Close closes the upstream connection

func (*UpstreamConnection) Connect

func (u *UpstreamConnection) Connect(ctx context.Context, config *UpstreamConfig) error

Connect establishes the TCP connection to the upstream service

func (*UpstreamConnection) ConnectionID

func (u *UpstreamConnection) ConnectionID() string

ConnectionID returns the parent connection ID

func (*UpstreamConnection) IdleDuration

func (u *UpstreamConnection) IdleDuration() time.Duration

IdleDuration returns how long the connection has been idle

func (*UpstreamConnection) IsClosed

func (u *UpstreamConnection) IsClosed() bool

IsClosed returns true if the connection is closed

func (*UpstreamConnection) LastActivity

func (u *UpstreamConnection) LastActivity() time.Time

LastActivity returns the time of the last activity

func (*UpstreamConnection) LocalAddr

func (u *UpstreamConnection) LocalAddr() net.Addr

LocalAddr returns the local address

func (*UpstreamConnection) Read

func (u *UpstreamConnection) Read(p []byte) (int, error)

Read reads data from the upstream connection

func (*UpstreamConnection) RemoteAddr

func (u *UpstreamConnection) RemoteAddr() net.Addr

RemoteAddr returns the remote address

func (*UpstreamConnection) State

State returns the current connection state

func (*UpstreamConnection) Stats

func (u *UpstreamConnection) Stats() UpstreamStats

Stats returns connection statistics

func (*UpstreamConnection) StreamID

func (u *UpstreamConnection) StreamID() int64

StreamID returns the associated stream ID

func (*UpstreamConnection) Write

func (u *UpstreamConnection) Write(p []byte) (int, error)

Write writes data to the upstream connection

type UpstreamConnectionState

type UpstreamConnectionState int32

UpstreamConnectionState represents the connection state

const (
	UpstreamStateConnecting UpstreamConnectionState = iota
	UpstreamStateConnected
	UpstreamStateClosing
	UpstreamStateClosed
)

func (UpstreamConnectionState) String

func (s UpstreamConnectionState) String() string

String returns the string representation

type UpstreamManager

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

UpstreamManager manages upstream TCP connections

func NewUpstreamManager

func NewUpstreamManager(targetAddr string, config *UpstreamConfig) *UpstreamManager

NewUpstreamManager creates a new upstream manager

func (*UpstreamManager) CloseAll

func (m *UpstreamManager) CloseAll()

CloseAll closes all upstream connections

func (*UpstreamManager) Connect

func (m *UpstreamManager) Connect(ctx context.Context, streamID int64, connectionID string) (*UpstreamConnection, error)

Connect creates and establishes a new upstream connection

func (*UpstreamManager) Count

func (m *UpstreamManager) Count() int

Count returns the number of active connections

func (*UpstreamManager) Get

func (m *UpstreamManager) Get(streamID int64) *UpstreamConnection

Get returns an upstream connection by stream ID

func (*UpstreamManager) Remove

func (m *UpstreamManager) Remove(streamID int64)

Remove removes an upstream connection

func (*UpstreamManager) Stats

Stats returns the manager statistics

type UpstreamManagerStats

type UpstreamManagerStats struct {
	TotalConnections  uint64
	ActiveConnections uint64
	ClosedConnections uint64
	TotalBytesRead    uint64
	TotalBytesWritten uint64
	ConnectFailures   uint64
}

UpstreamManagerStats holds statistics for the manager

type UpstreamStats

type UpstreamStats struct {
	StreamID     int64
	ConnectionID string
	TargetAddr   string
	State        UpstreamConnectionState
	BytesRead    uint64
	BytesWritten uint64
	CreatedAt    time.Time
	LastActivity time.Time
}

UpstreamStats holds statistics for an upstream connection

Jump to

Keyboard shortcuts

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