sockloop

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: 8 Imported by: 0

Documentation

Overview

Package sockloop provides packet processing loops for DNS tunneling. It manages the sending and receiving of DNS packets with support for batched operations and multipath routing.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrLoopClosed     = errors.New("packet loop is closed")
	ErrLoopRunning    = errors.New("packet loop is already running")
	ErrLoopNotRunning = errors.New("packet loop is not running")
	ErrEncodeFailed   = errors.New("packet encoding failed")
	ErrDecodeFailed   = errors.New("packet decoding failed")
	ErrSendFailed     = errors.New("packet send failed")
	ErrReceiveFailed  = errors.New("packet receive failed")
)

Common errors

Functions

func ProcessQueryFunc

func ProcessQueryFunc(process func(context.Context, []byte) ([]byte, error)) func(*net.UDPAddr, []byte) ([]byte, error)

ProcessQueryFunc creates a query handler function

Types

type BaseLoop

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

BaseLoop provides common loop functionality

func NewBaseLoop

func NewBaseLoop(config *LoopConfig, handler PacketHandler) *BaseLoop

NewBaseLoop creates a new base loop

func (*BaseLoop) Context

func (l *BaseLoop) Context() context.Context

Context returns the loop context

func (*BaseLoop) GetPacket

func (l *BaseLoop) GetPacket() *Packet

GetPacket gets a packet from the pool

func (*BaseLoop) IsRunning

func (l *BaseLoop) IsRunning() bool

IsRunning returns true if the loop is running

func (*BaseLoop) PutPacket

func (l *BaseLoop) PutPacket(pkt *Packet)

PutPacket returns a packet to the pool

func (*BaseLoop) QueueSend

func (l *BaseLoop) QueueSend(pkt *Packet) bool

QueueSend queues a packet for sending

func (*BaseLoop) QueueSendData

func (l *BaseLoop) QueueSendData(data []byte, peerAddr *net.UDPAddr, pathID int) bool

QueueSendData creates a packet and queues it for sending

func (*BaseLoop) RecordDecodeError

func (l *BaseLoop) RecordDecodeError()

RecordDecodeError records a decode error

func (*BaseLoop) RecordEncodeError

func (l *BaseLoop) RecordEncodeError()

RecordEncodeError records an encode error

func (*BaseLoop) RecordHandlerError

func (l *BaseLoop) RecordHandlerError()

RecordHandlerError records a handler error

func (*BaseLoop) RecordReceive

func (l *BaseLoop) RecordReceive(bytes int)

RecordReceive records a received packet

func (*BaseLoop) RecordReceiveError

func (l *BaseLoop) RecordReceiveError()

RecordReceiveError records a receive error

func (*BaseLoop) RecordSend

func (l *BaseLoop) RecordSend(bytes int)

RecordSend records a sent packet

func (*BaseLoop) RecordSendError

func (l *BaseLoop) RecordSendError()

RecordSendError records a send error

func (*BaseLoop) State

func (l *BaseLoop) State() LoopState

State returns the current loop state

func (*BaseLoop) Stats

func (l *BaseLoop) Stats() LoopStats

Stats returns the loop statistics

func (*BaseLoop) Stop

func (l *BaseLoop) Stop()

Stop stops the base loop

type ClientLoop

type ClientLoop struct {
	*BaseLoop
	// contains filtered or unexported fields
}

ClientLoop is the packet processing loop for the client

func NewClientLoop

func NewClientLoop(config *ClientLoopConfig, codec *dns.ClientCodec) *ClientLoop

NewClientLoop creates a new client packet loop

func (*ClientLoop) AddResolver

func (l *ClientLoop) AddResolver(id int, addr *net.UDPAddr) error

AddResolver adds a DNS resolver

func (*ClientLoop) GetResolvers

func (l *ClientLoop) GetResolvers() []*ResolverInfo

GetResolvers returns all resolvers

func (*ClientLoop) RemoveResolver

func (l *ClientLoop) RemoveResolver(id int) error

RemoveResolver removes a DNS resolver

func (*ClientLoop) ResolverStats

func (l *ClientLoop) ResolverStats() []ResolverInfo

ResolverStats returns statistics for all resolvers

func (*ClientLoop) SendData

func (l *ClientLoop) SendData(data []byte, pathID int) bool

SendData sends data to the server

func (*ClientLoop) SendDataToAll

func (l *ClientLoop) SendDataToAll(data []byte) bool

SendDataToAll sends data to all resolvers

func (*ClientLoop) SendPoll

func (l *ClientLoop) SendPoll(pathID int) bool

SendPoll sends a poll message

func (*ClientLoop) SendPollToAll

func (l *ClientLoop) SendPollToAll()

SendPollToAll sends a poll message to all resolvers

func (*ClientLoop) SetCallbacks

func (l *ClientLoop) SetCallbacks(onResponse, onPollResponse func(int, []byte), onError func(error))

SetCallbacks sets the callback functions

func (*ClientLoop) Start

func (l *ClientLoop) Start() error

Start starts the client loop

func (*ClientLoop) Stats

func (l *ClientLoop) Stats() ClientLoopStats

Stats returns the client loop statistics

func (*ClientLoop) Stop

func (l *ClientLoop) Stop()

Stop stops the client loop

type ClientLoopConfig

type ClientLoopConfig struct {
	// BaseConfig is the base loop configuration
	BaseConfig *LoopConfig

	// DNSTimeout is the timeout for DNS queries
	DNSTimeout time.Duration

	// PollInterval is the interval between poll messages
	PollInterval time.Duration

	// MaxRetries is the maximum number of retries for failed queries
	MaxRetries int

	// EnableMultipath enables sending to multiple resolvers
	EnableMultipath bool
}

ClientLoopConfig holds configuration for the client packet loop

func DefaultClientLoopConfig

func DefaultClientLoopConfig() *ClientLoopConfig

DefaultClientLoopConfig returns default client loop configuration

type ClientLoopStats

type ClientLoopStats struct {
	// Base stats
	LoopStats

	// Query stats
	QueriesSent       uint64
	ResponsesReceived uint64
	Timeouts          uint64
	Retries           uint64

	// Resolver stats
	ResolverCount int
}

ClientLoopStats holds statistics for the client loop

type LoopConfig

type LoopConfig struct {
	// BatchSize is the maximum number of packets to process in a batch
	BatchSize int

	// ReceiveTimeout is the timeout for receive operations
	ReceiveTimeout time.Duration

	// SendTimeout is the timeout for send operations
	SendTimeout time.Duration

	// BufferSize is the size of packet buffers
	BufferSize int

	// EnableGSO enables Generic Segmentation Offload
	EnableGSO bool

	// MaxGSOSegments is the maximum number of GSO segments
	MaxGSOSegments int
}

LoopConfig holds configuration for the packet loop

func DefaultLoopConfig

func DefaultLoopConfig() *LoopConfig

DefaultLoopConfig returns default loop configuration

type LoopState

type LoopState int32

LoopState represents the state of the packet loop

const (
	// LoopStateInitial indicates the loop is initialized but not started
	LoopStateInitial LoopState = iota

	// LoopStateRunning indicates the loop is running
	LoopStateRunning

	// LoopStateStopping indicates the loop is stopping
	LoopStateStopping

	// LoopStateStopped indicates the loop is stopped
	LoopStateStopped
)

func (LoopState) String

func (s LoopState) String() string

String returns the string representation of the loop state

type LoopStats

type LoopStats struct {
	// Packets received
	PacketsReceived uint64

	// Packets sent
	PacketsSent uint64

	// Bytes received
	BytesReceived uint64

	// Bytes sent
	BytesSent uint64

	// Receive errors
	ReceiveErrors uint64

	// Send errors
	SendErrors uint64

	// Encode errors
	EncodeErrors uint64

	// Decode errors
	DecodeErrors uint64

	// Handler errors
	HandlerErrors uint64
}

LoopStats holds statistics for the packet loop

type Packet

type Packet struct {
	// Data is the packet data
	Data []byte

	// PeerAddr is the remote address
	PeerAddr *net.UDPAddr

	// LocalAddr is the local address (for server)
	LocalAddr *net.UDPAddr

	// PathID identifies the path for multipath
	PathID int

	// Timestamp is when the packet was received/created
	Timestamp time.Time

	// IsPoll indicates if this is a poll packet
	IsPoll bool

	// MessageID is the DNS message ID
	MessageID uint16
}

Packet represents a network packet with metadata

func (*Packet) Clone

func (p *Packet) Clone() *Packet

Clone creates a copy of the packet

func (*Packet) Reset

func (p *Packet) Reset()

Reset clears all fields of the packet

func (*Packet) SetData

func (p *Packet) SetData(data []byte)

SetData sets the packet data, reusing the underlying buffer

type PacketDecoder

type PacketDecoder interface {
	// Decode decodes a DNS packet into data
	Decode(packet []byte) ([]byte, error)
}

PacketDecoder decodes DNS packets into data

type PacketEncoder

type PacketEncoder interface {
	// Encode encodes data into a DNS packet
	Encode(data []byte) ([]byte, uint16, error)
}

PacketEncoder encodes data into DNS packets

type PacketHandler

type PacketHandler interface {
	// HandlePacket processes a received packet
	// Returns response data to send, or nil if no response
	HandlePacket(ctx context.Context, packet *Packet) ([]byte, error)
}

PacketHandler handles received packets

type PacketHandlerFunc

type PacketHandlerFunc func(ctx context.Context, packet *Packet) ([]byte, error)

PacketHandlerFunc is a function that implements PacketHandler

func (PacketHandlerFunc) HandlePacket

func (f PacketHandlerFunc) HandlePacket(ctx context.Context, packet *Packet) ([]byte, error)

HandlePacket implements PacketHandler

type PacketPool

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

PacketPool manages a pool of reusable packets

func NewPacketPool

func NewPacketPool() *PacketPool

NewPacketPool creates a new packet pool

func (*PacketPool) Get

func (p *PacketPool) Get() *Packet

Get retrieves a packet from the pool

func (*PacketPool) Put

func (p *PacketPool) Put(pkt *Packet)

Put returns a packet to the pool

type PacketQueue

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

PacketQueue is a bounded queue for packets

func NewPacketQueue

func NewPacketQueue(size int, pool *PacketPool) *PacketQueue

NewPacketQueue creates a new packet queue

func (*PacketQueue) Close

func (q *PacketQueue) Close()

Close closes the queue

func (*PacketQueue) Dequeue

func (q *PacketQueue) Dequeue() *Packet

Dequeue removes and returns the next packet

func (*PacketQueue) DequeueBatch

func (q *PacketQueue) DequeueBatch(n int) []*Packet

DequeueBatch dequeues up to n packets

func (*PacketQueue) DequeueBlocking

func (q *PacketQueue) DequeueBlocking(ctx context.Context) *Packet

DequeueBlocking blocks until a packet is available

func (*PacketQueue) Enqueue

func (q *PacketQueue) Enqueue(pkt *Packet) bool

Enqueue adds a packet to the queue

func (*PacketQueue) Items

func (q *PacketQueue) Items() <-chan *Packet

Items returns the channel for receiving packets

func (*PacketQueue) Len

func (q *PacketQueue) Len() int

Len returns the current queue length

type ResolverInfo

type ResolverInfo struct {
	// ID is the resolver identifier
	ID int

	// Addr is the resolver address
	Addr *net.UDPAddr

	// Conn is the UDP connection to the resolver
	Conn *net.UDPConn

	// RTT is the estimated round-trip time
	RTT time.Duration

	// Available indicates if the resolver is available
	Available bool

	// LastResponse is the time of the last response
	LastResponse time.Time

	// Stats
	QueriesSent   uint64
	ResponsesRecv uint64
	Timeouts      uint64
	Errors        uint64
}

ResolverInfo holds information about a DNS resolver

type ServerLoop

type ServerLoop struct {
	*BaseLoop
	// contains filtered or unexported fields
}

ServerLoop is the packet processing loop for the server

func NewServerLoop

func NewServerLoop(config *ServerLoopConfig, codec *dns.ServerCodec) *ServerLoop

NewServerLoop creates a new server packet loop

func (*ServerLoop) Addr

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

Addr returns the listener address

func (*ServerLoop) SendErrorResponse

func (l *ServerLoop) SendErrorResponse(peerAddr *net.UDPAddr, rawQuery []byte, rcode int)

SendErrorResponse sends an error response to a client

func (*ServerLoop) SendResponse

func (l *ServerLoop) SendResponse(peerAddr *net.UDPAddr, rawQuery []byte, data []byte)

SendResponse sends a response to a client

func (*ServerLoop) SetCallbacks

func (l *ServerLoop) SetCallbacks(onQuery func(*net.UDPAddr, []byte) ([]byte, error), onError func(error))

SetCallbacks sets the callback functions

func (*ServerLoop) Start

func (l *ServerLoop) Start() error

Start starts the server loop

func (*ServerLoop) Stats

func (l *ServerLoop) Stats() ServerLoopStats

Stats returns the server loop statistics

func (*ServerLoop) Stop

func (l *ServerLoop) Stop()

Stop stops the server loop

type ServerLoopConfig

type ServerLoopConfig struct {
	// BaseConfig is the base loop configuration
	BaseConfig *LoopConfig

	// ListenAddr is the address to listen on
	ListenAddr string

	// Domain is the domain for DNS queries
	Domain string

	// ResponseTimeout is the timeout for generating responses
	ResponseTimeout time.Duration
}

ServerLoopConfig holds configuration for the server packet loop

func DefaultServerLoopConfig

func DefaultServerLoopConfig() *ServerLoopConfig

DefaultServerLoopConfig returns default server loop configuration

type ServerLoopStats

type ServerLoopStats struct {
	// Base stats
	LoopStats

	// Query stats
	QueriesReceived    uint64
	ResponsesSent      uint64
	ErrorResponsesSent uint64
}

ServerLoopStats holds statistics for the server loop

Jump to

Keyboard shortcuts

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