session

package
v0.1.59999 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package session: type aliases for types from ssu2 sub-packages. This file re-exports all external ssu2 types used within this package so that the implementation files need only change their package declaration.

Index

Constants

View Source
const (
	// StateInit is the initial state before handshake.
	StateInit = mod.StateInit
	// StateHandshaking is during the XK handshake.
	StateHandshaking = mod.StateHandshaking
	// StateEstablished means handshake complete, ready for data.
	StateEstablished = mod.StateEstablished
	// StateClosing is graceful shutdown in progress — corresponds to the
	// Termination block wait period (SSU2 spec §Termination).
	StateClosing = mod.StateClosing
	// StateClosed means connection is fully closed.
	StateClosed = mod.StateClosed
)
View Source
const (
	BlockTypeDateTime          = wire.BlockTypeDateTime
	BlockTypeOptions           = wire.BlockTypeOptions
	BlockTypeRouterInfo        = wire.BlockTypeRouterInfo
	BlockTypeI2NPMessage       = wire.BlockTypeI2NPMessage
	BlockTypeFirstFragment     = wire.BlockTypeFirstFragment
	BlockTypeFollowOnFragment  = wire.BlockTypeFollowOnFragment
	BlockTypeTermination       = wire.BlockTypeTermination
	BlockTypeRelayRequest      = wire.BlockTypeRelayRequest
	BlockTypeRelayResponse     = wire.BlockTypeRelayResponse
	BlockTypeRelayIntro        = wire.BlockTypeRelayIntro
	BlockTypePeerTest          = wire.BlockTypePeerTest
	BlockTypeNextNonce         = wire.BlockTypeNextNonce
	BlockTypeACK               = wire.BlockTypeACK
	BlockTypeAddress           = wire.BlockTypeAddress
	BlockTypeReserved14        = wire.BlockTypeReserved14
	BlockTypeRelayTagRequest   = wire.BlockTypeRelayTagRequest
	BlockTypeRelayTag          = wire.BlockTypeRelayTag
	BlockTypeNewToken          = wire.BlockTypeNewToken
	BlockTypePathChallenge     = wire.BlockTypePathChallenge
	BlockTypePathResponse      = wire.BlockTypePathResponse
	BlockTypeFirstPacketNumber = wire.BlockTypeFirstPacketNumber
	BlockTypeCongestion        = wire.BlockTypeCongestion
	BlockTypePadding           = wire.BlockTypePadding
)
View Source
const (
	TerminationNormalClose           = wire.TerminationNormalClose
	TerminationReceived              = wire.TerminationReceived
	TerminationIdleTimeout           = wire.TerminationIdleTimeout
	TerminationRouterShutdown        = wire.TerminationRouterShutdown
	TerminationDataPhaseAEADFailure  = wire.TerminationDataPhaseAEADFailure
	TerminationIncompatibleOptions   = wire.TerminationIncompatibleOptions
	TerminationIncompatibleSignature = wire.TerminationIncompatibleSignature
	TerminationClockSkew             = wire.TerminationClockSkew
	TerminationPaddingViolation      = wire.TerminationPaddingViolation
	TerminationAEADFramingError      = wire.TerminationAEADFramingError
	TerminationPayloadFormatError    = wire.TerminationPayloadFormatError
	TerminationSessionRequestError   = wire.TerminationSessionRequestError
	TerminationSessionCreatedError   = wire.TerminationSessionCreatedError
	TerminationSessionConfirmedError = wire.TerminationSessionConfirmedError
	TerminationTimeout               = wire.TerminationTimeout
	TerminationRISigVerifyFail       = wire.TerminationRISigVerifyFail
	TerminationSParamMissing         = wire.TerminationSParamMissing
	TerminationBanned                = wire.TerminationBanned
	TerminationBadToken              = wire.TerminationBadToken
	TerminationConnectionLimits      = wire.TerminationConnectionLimits
	TerminationIncompatibleVersion   = wire.TerminationIncompatibleVersion
	TerminationWrongNetID            = wire.TerminationWrongNetID
	TerminationReplacedByNewSession  = wire.TerminationReplacedByNewSession
)
View Source
const (
	HeaderTypeSessionRequest   = wire.HeaderTypeSessionRequest
	HeaderTypeSessionCreated   = wire.HeaderTypeSessionCreated
	HeaderTypeRetry            = wire.HeaderTypeRetry
	HeaderTypeTokenRequest     = wire.HeaderTypeTokenRequest
	HeaderTypeSessionConfirmed = wire.HeaderTypeSessionConfirmed
	HeaderTypeData             = wire.HeaderTypeData
	HeaderTypePeerTest         = wire.HeaderTypePeerTest
	HeaderTypeHolePunch        = wire.HeaderTypeHolePunch
)
View Source
const (
	MessageTypeSessionRequest   = wire.MessageTypeSessionRequest
	MessageTypeSessionCreated   = wire.MessageTypeSessionCreated
	MessageTypeSessionConfirmed = wire.MessageTypeSessionConfirmed
	MessageTypeData             = wire.MessageTypeData
	MessageTypePeerTest         = wire.MessageTypePeerTest
	MessageTypeRetry            = wire.MessageTypeRetry
	MessageTypeTokenRequest     = wire.MessageTypeTokenRequest
	MessageTypeHolePunch        = wire.MessageTypeHolePunch
)
View Source
const (
	ShortHeaderSize            = wire.ShortHeaderSize
	LongHeaderSize             = wire.LongHeaderSize
	EphemeralKeySize           = wire.EphemeralKeySize
	MACSize                    = wire.MACSize
	MinPacketSize              = wire.MinPacketSize
	MaxPacketSizeIPv4          = wire.MaxPacketSizeIPv4
	MaxPacketSizeIPv6          = wire.MaxPacketSizeIPv6
	SSU2ProtocolVersion        = wire.SSU2ProtocolVersion
	SSU2NetworkID              = wire.SSU2NetworkID
	SipHashIVSize              = wire.SipHashIVSize
	DataLengthFieldSize        = wire.DataLengthFieldSize
	TokenSize                  = wire.TokenSize
	MaxTokenCacheSize          = wire.MaxTokenCacheSize
	HeaderKeySize              = wire.HeaderKeySize
	MinPacketSizeForEncryption = wire.MinPacketSizeForEncryption
)
View Source
const (
	SSU2ProtocolName         = ssu2hs.SSU2ProtocolName
	PublishedKeyMinAge       = ssu2hs.PublishedKeyMinAge
	UnpublishedKeyMinAge     = ssu2hs.UnpublishedKeyMinAge
	KeyRotationCheckInterval = ssu2hs.KeyRotationCheckInterval
	KeyGracePeriod           = ssu2hs.KeyGracePeriod
	StaticKeySize            = ssu2hs.StaticKeySize
	IntroKeySize             = ssu2hs.IntroKeySize
	KeyStateActive           = ssu2hs.KeyStateActive
	KeyStatePendingRotation  = ssu2hs.KeyStatePendingRotation
	KeyStateRotating         = ssu2hs.KeyStateRotating
	KeyStateRetired          = ssu2hs.KeyStateRetired
)
View Source
const (
	CongestionFlagRequestACK  = reliability.CongestionFlagRequestACK
	CongestionFlagECN         = reliability.CongestionFlagECN
	MinCongestionWindow       = reliability.MinCongestionWindow
	InitialCongestionWindow   = reliability.InitialCongestionWindow
	MaxCongestionWindow       = reliability.MaxCongestionWindow
	SlowStart                 = reliability.SlowStart
	CongestionAvoidance       = reliability.CongestionAvoidance
	Recovery                  = reliability.Recovery
	DefaultMaxWindowSize      = reliability.DefaultMaxWindowSize
	MaxPacketNumber           = reliability.MaxPacketNumber
	InitialSlowStartThreshold = reliability.InitialSlowStartThreshold
	RTTKMultiplier            = reliability.RTTKMultiplier
	ClockGranularity          = reliability.ClockGranularity
	InitialRTO                = reliability.InitialRTO
	MinRTO                    = reliability.MinRTO
	MaxRTO                    = reliability.MaxRTO
)
View Source
const (
	NATUnknown        = path.NATUnknown
	NATNone           = path.NATNone
	NATCone           = path.NATCone
	NATRestricted     = path.NATRestricted
	NATPortRestricted = path.NATPortRestricted
	NATSymmetric      = path.NATSymmetric

	HolePunchRequested = path.HolePunchRequested
	HolePunchSent      = path.HolePunchSent
	HolePunchWaiting   = path.HolePunchWaiting
	HolePunchSuccess   = path.HolePunchSuccess
	HolePunchFailed    = path.HolePunchFailed

	ChallengeSent      = path.ChallengeSent
	ChallengeReceived  = path.ChallengeReceived
	ChallengeValidated = path.ChallengeValidated
	ChallengeFailed    = path.ChallengeFailed

	PeerTestRequest      = path.PeerTestRequest
	PeerTestRelay        = path.PeerTestRelay
	PeerTestResponse     = path.PeerTestResponse
	PeerTestResult       = path.PeerTestResult
	PeerTestProbe        = path.PeerTestProbe
	PeerTestReply        = path.PeerTestReply
	PeerTestConfirmation = path.PeerTestConfirmation

	RoleInitiator = path.RoleInitiator
	RoleRelay     = path.RoleRelay
	RoleResponder = path.RoleResponder

	TestRequested = path.TestRequested
	TestRelayed   = path.TestRelayed
	TestProbed    = path.TestProbed
	TestComplete  = path.TestComplete
	TestFailed    = path.TestFailed
)

Variables

View Source
var (
	NewSSU2Config        = ssu2config.NewSSU2Config
	NewSSU2Addr          = ssu2config.NewSSU2Addr
	NewMockSSU2Addr      = ssu2config.NewMockSSU2Addr
	GenerateConnectionID = ssu2config.GenerateConnectionID
)
View Source
var (
	NewSSU2Block                        = wire.NewSSU2Block
	NewSSU2Packet                       = wire.NewSSU2Packet
	NewBlockRouter                      = wire.NewBlockRouter
	SerializeBlocks                     = wire.SerializeBlocks
	DeserializeBlocks                   = wire.DeserializeBlocks
	FindBlockByType                     = wire.FindBlockByType
	IsKnownBlockType                    = wire.IsKnownBlockType
	BlockTypeName                       = wire.BlockTypeName
	GetBlockTypeName                    = wire.GetBlockTypeName
	GetBlockCategory                    = wire.GetBlockCategory
	AllBlockTypes                       = wire.AllBlockTypes
	ExtractConnectionID                 = wire.ExtractConnectionID
	ParseNewTokenBlock                  = wire.ParseNewTokenBlock
	EncodeAddressBlock                  = wire.EncodeAddressBlock
	DecodeAddressBlock                  = wire.DecodeAddressBlock
	NewSipHashLengthModifierDirectional = wire.NewSipHashLengthModifierDirectional
	NewHeaderProtectorManager           = wire.NewHeaderProtectorManager
	NewTokenCache                       = wire.NewTokenCache
	NewTokenCacheWithMaxSize            = wire.NewTokenCacheWithMaxSize
	IntroKeyFromRouterAddress           = wire.IntroKeyFromRouterAddress
	StaticKeyFromRouterAddress          = wire.StaticKeyFromRouterAddress
)
View Source
var (
	NewHandshakeHandler         = ssu2hs.NewHandshakeHandler
	NewHandshakeHandlerWithKeys = ssu2hs.NewHandshakeHandlerWithKeys
	ParseOptionsBlock           = ssu2hs.ParseOptionsBlock
	NewKeyRotationManager       = ssu2hs.NewKeyRotationManager
	GenerateNewStaticKey        = ssu2hs.GenerateNewStaticKey
	GenerateNewIntroKey         = ssu2hs.GenerateNewIntroKey
)
View Source
var (
	NewACKHandler                  = reliability.NewACKHandler
	NewCongestionController        = reliability.NewCongestionController
	NewCongestionControllerWithMTU = reliability.NewCongestionControllerWithMTU
	NewRTTEstimator                = reliability.NewRTTEstimator
	NewReceiveWindow               = reliability.NewReceiveWindow
	NewKeepaliveManager            = reliability.NewKeepaliveManager
	DecodeCongestionBlock          = reliability.DecodeCongestionBlock
	EncodeCongestionBlock          = reliability.EncodeCongestionBlock
	SortDescDedupPackets           = reliability.SortDescDedupPackets
)
View Source
var (
	NewPathValidator             = path.NewPathValidator
	DecodeRelayIntro             = path.DecodeRelayIntro
	DecodeRelayRequest           = path.DecodeRelayRequest
	DecodeRelayResponse          = path.DecodeRelayResponse
	DecodePeerTestBlock          = path.DecodePeerTestBlock
	EncodeRelayRequest           = path.EncodeRelayRequest
	EncodeRelayResponse          = path.EncodeRelayResponse
	EncodeRelayIntro             = path.EncodeRelayIntro
	EncodeRelayTagRequest        = path.EncodeRelayTagRequest
	EncodeRelayTag               = path.EncodeRelayTag
	EncodePeerTestBlock          = path.EncodePeerTestBlock
	VerifyRelayRequestSignature  = path.VerifyRelayRequestSignature
	VerifyRelayResponseSignature = path.VerifyRelayResponseSignature
	VerifyPeerTestSignature      = path.VerifyPeerTestSignature
)

Functions

This section is empty.

Types

type ACKHandler

type ACKHandler = reliability.ACKHandler

type AddressBlock added in v0.1.56

type AddressBlock = wire.AddressBlock

type BlockHandler added in v0.1.56

type BlockHandler = wire.BlockHandler

type BlockHandlerFunc added in v0.1.56

type BlockHandlerFunc = wire.BlockHandlerFunc

type BlockRouter

type BlockRouter = wire.BlockRouter

type BlockRouterStats added in v0.1.56

type BlockRouterStats = wire.BlockRouterStats

type BlockTypeCategory added in v0.1.56

type BlockTypeCategory = wire.BlockTypeCategory

type ChaChaObfuscationModifier added in v0.1.56

type ChaChaObfuscationModifier = wire.ChaChaObfuscationModifier

type CongestionController

type CongestionController = reliability.CongestionController

type CongestionControllerAccessor

type CongestionControllerAccessor = path.CongestionControllerAccessor

type CongestionState

type CongestionState = reliability.CongestionState

type CongestionStats

type CongestionStats = reliability.CongestionStats

type ConnState

type ConnState = mod.ConnState

ConnState is an alias for mod.ConnState, the shared connection lifecycle type. SSU2 uses mod.ConnState directly, including the StateClosing state which mod now provides for graceful-shutdown semantics (e.g. the SSU2 Termination block wait period per spec §Termination).

type DataHandler

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

DataHandler manages Data message processing for SSU2 connections. It handles I2NP message extraction, fragmentation/reassembly, and maintains a queue of complete messages ready for the application layer.

Data messages (Type 6) can contain: - BlockTypeI2NPMessage (Type 3): Complete I2NP messages - BlockTypeFirstFragment (Type 4): First fragment of large message - BlockTypeFollowOnFragment (Type 5): Subsequent fragments - All other 17 block types (DateTime, ACK, Relay*, PeerTest, etc.)

func NewDataHandler

func NewDataHandler(queueSize int) *DataHandler

NewDataHandler creates a new Data message handler. queueSize determines how many complete messages can be buffered.

func (*DataHandler) CleanupExpiredFragments

func (h *DataHandler) CleanupExpiredFragments(timeout time.Duration) int

CleanupExpiredFragments removes fragment sets that haven't been updated within the specified timeout. Should be called periodically.

func (*DataHandler) Clear

func (h *DataHandler) Clear()

Clear removes all queued messages and fragments.

func (*DataHandler) Close

func (h *DataHandler) Close()

Close stops the fragment reaper goroutine.

func (*DataHandler) GetBlockRouter

func (h *DataHandler) GetBlockRouter() *BlockRouter

GetBlockRouter returns the block router for registering external handlers.

func (*DataHandler) GetFragmentCount

func (h *DataHandler) GetFragmentCount() int

GetFragmentCount returns the number of incomplete fragment sets.

func (*DataHandler) GetMessage

func (h *DataHandler) GetMessage() []byte

GetMessage retrieves the next complete I2NP message from the queue. Returns nil if no messages are available (non-blocking).

func (*DataHandler) GetMessageBlocking

func (h *DataHandler) GetMessageBlocking(timeout time.Duration) []byte

GetMessageBlocking waits for the next message with optional timeout. Returns nil if timeout expires.

func (*DataHandler) GetStats

func (h *DataHandler) GetStats() DataHandlerStats

GetStats returns a copy of current statistics.

func (*DataHandler) HasMessages

func (h *DataHandler) HasMessages() bool

HasMessages returns true if messages are available in the queue.

func (*DataHandler) MessageChan

func (h *DataHandler) MessageChan() <-chan []byte

MessageChan returns the receive-only channel for complete I2NP messages. Used by SSU2Conn.Read to block until a message is available.

func (*DataHandler) ProcessDataPacket

func (h *DataHandler) ProcessDataPacket(packet *SSU2Packet) ([]*SSU2Block, error)

ProcessDataPacket processes a Data packet and extracts I2NP messages. Returns extracted blocks and any error encountered. All 20 SSU2 block types are explicitly handled.

func (*DataHandler) SetCallbacks

func (h *DataHandler) SetCallbacks(callbacks DataHandlerCallbacks)

SetCallbacks sets the callback handlers for block types.

func (*DataHandler) StartReaper

func (h *DataHandler) StartReaper()

StartReaper launches a background goroutine that periodically removes incomplete fragment sets older than fragmentTimeout.

type DataHandlerCallbacks

type DataHandlerCallbacks struct {
	// OnTermination is called when a Termination block is received.
	// validDataReceived is the number of valid data packets received (8-byte uint64);
	// reason is the termination code; additionalData is the remaining bytes per SSU2 spec.
	OnTermination func(validDataReceived uint64, reason uint8, additionalData []byte)

	// OnNewToken is called when a NewToken block is received
	OnNewToken func(token []byte)

	// OnRelayRequest is called when a RelayRequest block is received
	OnRelayRequest func(block *SSU2Block) error

	// OnRelayResponse is called when a RelayResponse block is received
	OnRelayResponse func(block *SSU2Block) error

	// OnRelayIntro is called when a RelayIntro block is received
	OnRelayIntro func(block *SSU2Block) error

	// OnRelayTagRequest is called when a RelayTagRequest block is received
	OnRelayTagRequest func(block *SSU2Block) error

	// OnRelayTag is called when a RelayTag block is received
	OnRelayTag func(block *SSU2Block) error

	// OnPeerTest is called when a PeerTest block is received
	OnPeerTest func(block *SSU2Block) error

	// OnPathChallenge is called when a PathChallenge block is received
	OnPathChallenge func(data []byte) error

	// OnPathResponse is called when a PathResponse block is received
	OnPathResponse func(data []byte) error

	// OnRouterInfo is called when a RouterInfo block is received
	OnRouterInfo func(data []byte) error

	// OnOptions is called when an Options block is received
	OnOptions func(data []byte) error

	// OnAddress is called when an Address block is received
	OnAddress func(data []byte) error

	// OnACK is called when an ACK block is received
	OnACK func(block *SSU2Block) error

	// OnDateTime is called when a DateTime block is received
	OnDateTime func(timestamp uint32) error

	// OnNextNonce is called when a NextNonce block is received.
	// The newNonce is the 8-byte value signaling the peer's next send nonce.
	OnNextNonce func(newNonce uint64) error

	// OnFirstPacketNumber is called when a FirstPacketNumber block is received.
	// packetNumber is the initial packet number for the data phase.
	OnFirstPacketNumber func(packetNumber uint32) error

	// OnCongestion is called when a Congestion block is received.
	// flags is the congestion flag byte per spec: bit 0 = request immediate ACK, bit 1 = ECN.
	OnCongestion func(flags uint8) error

	// VerifyPeerTestSignature is called to verify a PeerTest block's signature
	// before dispatching to OnPeerTest. Per SSU2 spec §Peer Test, signatures
	// MUST be verified before acting on the message (G-2). If nil, blocks with
	// mandatory signatures (messages 1-4) are rejected.
	VerifyPeerTestSignature func(block *PeerTestBlock) error

	// VerifyRelayRequestSignature is called to verify a RelayRequest block's
	// signature before dispatching to OnRelayRequest. Per SSU2 spec §Relay
	// Request, signatures MUST be verified (G-2). If nil, blocks are rejected.
	VerifyRelayRequestSignature func(block *RelayRequestBlock) error

	// VerifyRelayResponseSignature is called to verify a RelayResponse block's
	// signature before dispatching to OnRelayResponse. Per SSU2 spec §Relay
	// Response, signatures MUST be verified for code 0 and code >= 64 (G-2).
	// If nil, signed responses are rejected.
	VerifyRelayResponseSignature func(block *RelayResponseBlock) error

	// VerifyRelayIntroSignature is called to verify a RelayIntro block's
	// signature before dispatching to OnRelayIntro. Per SSU2 spec §Relay
	// Intro, signatures MUST be verified (G-2). If nil, blocks are rejected.
	VerifyRelayIntroSignature func(block *RelayIntroBlock) error
}

DataHandlerCallbacks defines optional callbacks for block types that need external handling.

type DataHandlerStats

type DataHandlerStats struct {
	MessagesReceived    uint64 // Complete messages received
	FragmentsReceived   uint64 // Total fragments received
	MessagesReassembled uint64 // Messages successfully reassembled
	MessagesDropped     uint64 // Messages dropped (timeout, errors)
	BlocksProcessed     uint64 // Total blocks processed
	UnknownBlocks       uint64 // Unknown block types received
}

DataHandlerStats tracks statistics for monitoring and debugging.

type FragmentSet

type FragmentSet struct {
	MessageID       uint32           // I2NP message identifier
	I2NPType        uint8            // I2NP message type from First Fragment
	ShortExpiration uint32           // I2NP short expiration from First Fragment
	Fragments       map[uint8][]byte // Fragment number -> data
	ReceivedSize    uint32           // Bytes received so far
	HasLast         bool             // Whether we've received the last fragment
	HasFirst        bool             // Whether we've received the first fragment
	LastFragNum     uint8            // Fragment number of the last fragment
	CreatedAt       time.Time        // When first fragment arrived
	LastUpdate      time.Time        // Last fragment received time
}

FragmentSet represents a message being reassembled from fragments.

type HandshakeHandler

type HandshakeHandler = ssu2hs.HandshakeHandler

type HeaderProtector added in v0.1.56

type HeaderProtector = wire.HeaderProtector

type HeaderProtectorManager

type HeaderProtectorManager = wire.HeaderProtectorManager

type HeaderType

type HeaderType = wire.HeaderType

type HolePunchAttempt

type HolePunchAttempt = path.HolePunchAttempt

type HolePunchCoordinator

type HolePunchCoordinator = path.HolePunchCoordinator

type HolePunchState

type HolePunchState = path.HolePunchState

type IntroducerInfo

type IntroducerInfo = path.IntroducerInfo

type IntroducerRegistry

type IntroducerRegistry = path.IntroducerRegistry

type KeepaliveManager

type KeepaliveManager = reliability.KeepaliveManager

type KeyRotationCallback

type KeyRotationCallback = ssu2hs.KeyRotationCallback

type KeyRotationManager

type KeyRotationManager = ssu2hs.KeyRotationManager

type KeyRotationStatus

type KeyRotationStatus = ssu2hs.KeyRotationStatus

type KeyState

type KeyState = ssu2hs.KeyState

type ListenerRef

type ListenerRef = path.ListenerRef

type ManagedKey

type ManagedKey = ssu2hs.ManagedKey

type NATType

type NATType = path.NATType

type NewTokenBlock added in v0.1.56

type NewTokenBlock = wire.NewTokenBlock

type OptionsParams

type OptionsParams = ssu2hs.OptionsParams

type PacketRouter

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

PacketRouter routes incoming SSU2 packets to appropriate connection sessions based on connection ID or creates new sessions for handshake packets.

Design rationale: - SSU2 uses connection IDs to multiplex multiple sessions over a single UDP socket - The router extracts the destination connection ID from the encrypted header - Handshake packets (SessionRequest) may have connection ID 0 and trigger new sessions - Data packets are routed to existing sessions by connection ID

Thread Safety: All methods are thread-safe via the sessionMutex.

func NewPacketRouter

func NewPacketRouter(newSessionHandler func(*net.UDPAddr, *SSU2Packet) (*SSU2Conn, error)) *PacketRouter

NewPacketRouter creates a new packet router with an empty session table. The newSessionHandler callback is invoked when handshake packets arrive for unknown connection IDs, allowing the listener to create new sessions.

Parameters:

  • newSessionHandler: Callback to create new sessions for handshake packets. May be nil if the router only handles existing sessions.

Returns a new PacketRouter ready to route packets.

func (*PacketRouter) AddSession

func (pr *PacketRouter) AddSession(conn *SSU2Conn) error

AddSession registers a connection in the routing table. The connection's connection ID is used as the routing key.

Parameters:

  • conn: The SSU2Conn to register

Returns error if the connection ID is already registered.

func (*PacketRouter) ExtractConnectionID

func (pr *PacketRouter) ExtractConnectionID(header []byte) (uint64, error)

ExtractConnectionID extracts the destination connection ID from an encrypted header.

Design: The connection ID location depends on the header format per ssu2.rst. For short headers (16 bytes): bytes 8-15 contain the destination connection ID For long headers (32 bytes): bytes 8-15 contain the destination connection ID

Note: The header must already be decrypted before calling this method. The connection ID is encoded in network byte order (big-endian).

Parameters:

  • header: The decrypted header bytes

Returns:

  • uint64: The destination connection ID
  • error: If header is invalid or too short

func (*PacketRouter) GetSession

func (pr *PacketRouter) GetSession(connID uint64) *SSU2Conn

GetSession retrieves a connection by its connection ID. Returns nil if no session exists for the given ID.

Parameters:

  • connID: The connection ID to look up

Returns the SSU2Conn or nil if not found.

func (*PacketRouter) IsHandshakePacket

func (pr *PacketRouter) IsHandshakePacket(msgType uint8) bool

IsHandshakePacket returns true if the message type represents a handshake packet that can initiate a new connection session.

Handshake packets per ssu2.rst: - SessionRequest (0): Initial handshake message - TokenRequest (10): Request for retry token

SessionCreated (1) and SessionConfirmed (2) are not included because they require an existing session initiated by SessionRequest.

Parameters:

  • msgType: The SSU2 message type (0-11)

Returns true if this message type can create a new session.

func (*PacketRouter) RemoveSession

func (pr *PacketRouter) RemoveSession(connID uint64)

RemoveSession unregisters a connection from the routing table. This should be called when a connection closes.

Parameters:

  • connID: The connection ID to remove

func (*PacketRouter) RoutePacket

func (pr *PacketRouter) RoutePacket(packet *SSU2Packet, remoteAddr *net.UDPAddr) error

RoutePacket routes an incoming packet to the appropriate session. For handshake packets with unknown connection IDs, invokes newSessionHandler. For data packets, routes to existing session or returns error.

Parameters:

  • packet: The SSU2Packet to route
  • remoteAddr: The UDP address the packet was received from

Returns error if routing fails or session doesn't exist.

func (*PacketRouter) SessionCount

func (pr *PacketRouter) SessionCount() int

SessionCount returns the current number of registered sessions. Useful for monitoring and debugging.

type PathChallenge

type PathChallenge = path.PathChallenge

type PathChallengeState

type PathChallengeState = path.PathChallengeState

type PathValidationConn

type PathValidationConn = path.PathValidationConn

type PathValidator

type PathValidator = path.PathValidator

type PeerTest

type PeerTest = path.PeerTest

type PeerTestBlock

type PeerTestBlock = path.PeerTestBlock

type PeerTestManager

type PeerTestManager = path.PeerTestManager

type PeerTestMessageCode

type PeerTestMessageCode = path.PeerTestMessageCode

type PeerTestRole

type PeerTestRole = path.PeerTestRole

type PeerTestState

type PeerTestState = path.PeerTestState

type PendingACK

type PendingACK = reliability.PendingACK

type PendingPacket

type PendingPacket struct {
	Packet           *SSU2Packet
	PlaintextPayload []byte // pre-encryption payload for retransmit
	SentTime         time.Time
	Retries          int
	NextRetry        time.Time
}

PendingPacket tracks an outbound packet awaiting acknowledgment.

type PendingSession

type PendingSession = path.PendingSession

type RTTEstimator

type RTTEstimator = reliability.RTTEstimator

type ReceiveWindow

type ReceiveWindow = reliability.ReceiveWindow

type RegisteredIntroducer

type RegisteredIntroducer = path.RegisteredIntroducer

type RelayIntroBlock

type RelayIntroBlock = path.RelayIntroBlock

type RelayManager

type RelayManager = path.RelayManager

type RelayRequestBlock

type RelayRequestBlock = path.RelayRequestBlock

type RelayResponseBlock

type RelayResponseBlock = path.RelayResponseBlock

type RelayTag

type RelayTag = path.RelayTag

type RelayTagBlock

type RelayTagBlock = path.RelayTagBlock

type RelayTagRequestBlock

type RelayTagRequestBlock = path.RelayTagRequestBlock

type Router

type Router interface {
	// AddSession registers a connection so it can receive routed packets.
	AddSession(conn *SSU2Conn) error

	// RemoveSession unregisters a connection by its connection ID.
	RemoveSession(connID uint64)

	// GetSession retrieves a registered connection by its connection ID.
	// Returns nil if no session with that ID exists.
	GetSession(connID uint64) *SSU2Conn

	// RoutePacket dispatches a received packet to its owning session.
	RoutePacket(packet *wire.SSU2Packet, remoteAddr *net.UDPAddr) error

	// SessionCount returns the number of active sessions.
	SessionCount() int
}

Router abstracts routing SSU2 packets to established sessions. *PacketRouter satisfies this interface.

Callers that dispatch incoming packets can depend on Router rather than on the concrete *PacketRouter, enabling easier testing and alternative routing strategies.

type SSU2Addr

type SSU2Addr = ssu2config.SSU2Addr

type SSU2Block

type SSU2Block = wire.SSU2Block

type SSU2Config

type SSU2Config = ssu2config.SSU2Config

type SSU2Conn

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

SSU2Conn implements net.Conn for SSU2 transport connections over UDP. It integrates HandshakeHandler, DataHandler, and ACKHandler to provide a complete connection implementation following the SSU2 protocol.

SSU2Conn handles: - XK pattern handshake (SessionRequest/Created/Confirmed) - Reliable ordered data delivery with ACKs - Fragment reassembly for large messages - Out-of-order packet buffering - RTT estimation and congestion control - Keepalive mechanism

Thread Safety: All public methods are thread-safe.

func NewMockSSU2Conn

func NewMockSSU2Conn(connID uint64) *SSU2Conn

func NewSSU2Conn

func NewSSU2Conn(
	underlying net.PacketConn,
	remoteAddr *net.UDPAddr,
	config *SSU2Config,
	initiator bool,
	staticKey []byte,
	remoteStaticKey []byte,
) (*SSU2Conn, error)

NewSSU2Conn creates a new SSU2 connection. The connection starts in StateInit and must call Handshake() before data transfer.

Parameters: - underlying: UDP PacketConn for sending/receiving - remoteAddr: Peer's UDP address - config: SSU2 configuration (validated before use) - initiator: true if we initiate handshake, false if responding - staticKey: our static X25519 private key (32 bytes) - remoteStaticKey: peer's static public key (32 bytes, required for initiator) NewSSU2Conn creates a new SSU2 connection. The connection starts in StateInit and must call Handshake() before data transfer.

Parameters: - underlying: UDP PacketConn for sending/receiving - remoteAddr: Peer's UDP address - config: SSU2 configuration (validated before use) - initiator: true if we initiate handshake, false if responding - staticKey: our static X25519 private key (32 bytes) - remoteStaticKey: peer's static public key (32 bytes, required for initiator)

func (*SSU2Conn) Close

func (h *SSU2Conn) Close() error

func (*SSU2Conn) CloseWithReason

func (h *SSU2Conn) CloseWithReason(reason TerminationReason, additionalData []byte) error

CloseWithReason sends a Termination block with the given reason code and optional additional data, then closes the connection. Per spec §Termination, the data is: validDataPacketsReceived (8 bytes) + reason (1 byte) + additional data (optional). CloseWithReason sends a Termination block with the given reason code and optional additional data, then closes the connection. Per spec §Termination, the data is: validDataPacketsReceived (8 bytes) + reason (1 byte) + additional data (optional).

func (*SSU2Conn) GetRemoteAddr

func (h *SSU2Conn) GetRemoteAddr() *net.UDPAddr

GetRemoteAddr returns the current remote UDP address (implements PathValidationConn). GetRemoteAddr returns the current remote UDP address (implements PathValidationConn).

func (*SSU2Conn) GetSSU2Addr

func (h *SSU2Conn) GetSSU2Addr() *SSU2Addr

GetSSU2Addr returns the SSU2 address associated with this connection. It exposes the otherwise-unexported ssu2Addr field for use by outer packages such as ssu2/server tests.

func (*SSU2Conn) GetState

func (h *SSU2Conn) GetState() ConnState

GetState returns the current connection state. GetState returns the current connection state.

func (*SSU2Conn) Handshake

func (h *SSU2Conn) Handshake(ctx context.Context) error

Handshake performs the SSU2 XK pattern handshake. For initiators: sends SessionRequest, receives SessionCreated, sends SessionConfirmed For responders: receives SessionRequest, sends SessionCreated, receives SessionConfirmed

After successful handshake, connection state transitions to StateEstablished.

Context cancellation semantics: ------------------------------- The supplied context is honored via socket deadlines set before each blocking receive. Cancellation does NOT directly interrupt an in-progress ReadFrom syscall; instead, cancellation is detected when:

  1. The next read times out (deadline expires), OR
  2. Control returns to Handshake code that checks ctx.Err()

This means cancellation latency equals the handshake timeout (typically a few seconds). If you require immediate cancellation, you must Close() the connection from another goroutine when ctx.Done() fires.

This design avoids the complexity of a watchdog goroutine racing with handshake completion, at the cost of bounded cancellation latency.

func (*SSU2Conn) IsInitiator

func (h *SSU2Conn) IsInitiator() bool

IsInitiator reports whether this connection was created as the initiating side of the SSU2 handshake.

func (*SSU2Conn) LocalAddr

func (h *SSU2Conn) LocalAddr() net.Addr

LocalAddr implements net.Conn.LocalAddr. LocalAddr implements net.Conn.LocalAddr.

func (*SSU2Conn) MessageChan

func (h *SSU2Conn) MessageChan() <-chan []byte

MessageChan returns a receive-only channel of complete I2NP messages. This is an alternative delivery path to Read(); both paths consume from the same underlying channel, so they are mutually exclusive. Using both concurrently will cause messages to race to whichever receiver is ready, resulting in silent message loss.

IMPORTANT: Do not use MessageChan() and Read() concurrently on the same connection. This method returns a closed channel (panic-free sentinel) if Read() has already been called, enforcing mutual exclusivity. See MEDIUM-1.

func (*SSU2Conn) Read

func (h *SSU2Conn) Read(b []byte) (int, error)

Read implements net.Conn.Read. Reads data from the connection, reassembling I2NP messages from Data packets. Blocks until data is available, the read deadline expires, or the connection closes.

If a previous Read call did not consume a complete message (because the caller's buffer was too small), this Read returns the remainder of that message first before fetching a new one from the DataHandler.

func (*SSU2Conn) RecvStats

func (h *SSU2Conn) RecvStats() map[string]uint64

RecvStats returns error counters from the receive loop for observability. Keys: "read_errors", "parse_errors", "decrypt_errors". RecvStats returns error counters from the receive loop for observability. Keys: "read_errors", "parse_errors", "decrypt_errors".

func (*SSU2Conn) RemoteAddr

func (h *SSU2Conn) RemoteAddr() net.Addr

RemoteAddr implements net.Conn.RemoteAddr. RemoteAddr implements net.Conn.RemoteAddr.

func (*SSU2Conn) SendToAddress

func (h *SSU2Conn) SendToAddress(block *SSU2Block, addr *net.UDPAddr) error

SendToAddress sends a block to a specific UDP address (implements PathValidationConn). SendToAddress sends a block to a specific UDP address (implements PathValidationConn).

func (*SSU2Conn) SetDataHandlerCallbacks

func (h *SSU2Conn) SetDataHandlerCallbacks(cbs DataHandlerCallbacks)

SetDataHandlerCallbacks wires application-level callbacks for SSU2 block types received during the data phase. Call before Handshake() completes to ensure callbacks are active from the first data packet. Safe to call concurrently with an active connection; updates take effect on the next inbound packet. SetDataHandlerCallbacks wires application-level callbacks for SSU2 block types received during the data phase. Call before Handshake() completes to ensure callbacks are active from the first data packet. Safe to call concurrently with an active connection; updates take effect on the next inbound packet.

func (*SSU2Conn) SetDeadline

func (h *SSU2Conn) SetDeadline(t time.Time) error

SetDeadline implements net.Conn.SetDeadline. SetDeadline implements net.Conn.SetDeadline.

func (*SSU2Conn) SetOwnsUnderlying

func (h *SSU2Conn) SetOwnsUnderlying(v bool)

SetOwnsUnderlying marks whether this connection owns the underlying PacketConn. When true, CloseWithReason will close the PacketConn. When false (shared socket scenarios), the PacketConn is left open.

func (*SSU2Conn) SetReadDeadline

func (h *SSU2Conn) SetReadDeadline(t time.Time) error

SetReadDeadline implements net.Conn.SetReadDeadline. SetReadDeadline implements net.Conn.SetReadDeadline.

func (*SSU2Conn) SetRemoteAddr

func (h *SSU2Conn) SetRemoteAddr(addr *net.UDPAddr) error

SetRemoteAddr updates the remote address after successful path validation (implements PathValidationConn). SetRemoteAddr updates the remote address after successful path validation (implements PathValidationConn).

func (*SSU2Conn) SetWriteDeadline

func (h *SSU2Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements net.Conn.SetWriteDeadline. SetWriteDeadline implements net.Conn.SetWriteDeadline.

func (*SSU2Conn) Write

func (h *SSU2Conn) Write(b []byte) (int, error)

Write implements net.Conn.Write. Writes data to the connection. If the data exceeds the per-packet payload capacity (determined by MTU), it is automatically split into FirstFragment and FollowOnFragment blocks per SSU2 spec §FirstFragment/§FollowOnFragment.

For unfragmented messages, b is sent as-is in a BlockTypeI2NPMessage block. Per the SSU2 spec, block type 3 (I2NP) data must already contain the 9-byte I2NP short header: [I2NPType:1][MessageID:4][ShortExpiry:4] followed by the message body. The caller is responsible for prepending this header.

For fragmented messages, the implementation generates its own MessageID and ShortExpiry for the FirstFragment/FollowOnFragment blocks, treating b[0] as the I2NP type byte and the rest as body data.

func (*SSU2Conn) WriteBlocks

func (h *SSU2Conn) WriteBlocks(blocks []*SSU2Block) error

WriteBlocks sends the provided SSU2 blocks as individual Data packets (one packet per block). Unlike Write, this bypasses the BlockTypeI2NPMessage wrapper and sends pre-built blocks directly. Use this to send fragment blocks (BlockTypeFirstFragment / BlockTypeFollowOnFragment) for large I2NP messages.

type SSU2Packet

type SSU2Packet = wire.SSU2Packet

type SSU2PaddingModifier

type SSU2PaddingModifier = wire.SSU2PaddingModifier

type SendReceiver

type SendReceiver = reliability.SendReceiver

type SipHashLengthModifier added in v0.1.56

type SipHashLengthModifier = wire.SipHashLengthModifier

type TerminationReason

type TerminationReason = wire.TerminationReason

type TestResult

type TestResult = path.TestResult

type Token

type Token = wire.Token

type TokenCache added in v0.1.56

type TokenCache = wire.TokenCache

type TokenCacheAccessor

type TokenCacheAccessor = path.TokenCacheAccessor

Jump to

Keyboard shortcuts

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