lib

package
v0.0.0-...-86ae88e Latest Latest
Warning

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

Go to latest
Published: May 27, 2024 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SynReceived          = 1 // 3-way handshake server state
	SynAckSent           = 2 // 3-way handshake server state
	AckReceived          = 3 // 3-way handshake server state
	SynSent              = 1 // 3-way handshake client state
	SynAckReceived       = 2 // 3-way handshake client state
	AckSent              = 3 // 3-way handshake client state
	CallerFinSent        = 1 // 4-way termination caller state
	CallerFinAckReceived = 2 // 4-way termination caller state
	CallerAckSent        = 3 // 4-way termination caller state
	RespFinReceived      = 1 // 4-way termination responder state
	RespFinAckSent       = 2 // 4-way termination responder state
	RespAckReceived      = 3 // 4-way termination responder state
)
View Source
const (
	// PCP flag constants
	URGFlag uint8 = 1 << 5
	ACKFlag uint8 = 1 << 4
	PSHFlag uint8 = 1 << 3
	RSTFlag uint8 = 1 << 2
	SYNFlag uint8 = 1 << 1
	FINFlag uint8 = 1 << 0
)

Flag constants

View Source
const (
	Red   = "\033[31m"
	Reset = "\033[0m"
)
View Source
const (
	TcpOptionsMaxLength   = 40
	TcpHeaderLength       = 20 //options not included
	TcpPseudoHeaderLength = 12
	IpHeaderMaxLength     = 60
)

Variables

View Source
var (
	PoolDebug = rp.Debug

	Pool *rp.RingPool
)

Functions

func CalculateChecksum

func CalculateChecksum(buffer []byte) uint16

func ExtractIpPayload

func ExtractIpPayload(ipFrame []byte) (int, error)

Function to extract payload from an IP packet

func GenerateISN

func GenerateISN() (uint32, error)

func NewPayload

func NewPayload(params ...interface{}) rp.DataInterface

Define a function that creates a new instance of ConcreteData

func SeqIncrement

func SeqIncrement(seq uint32) uint32

func SeqIncrementBy

func SeqIncrementBy(seq, inc uint32) uint32

func SetEmptySlice

func SetEmptySlice(length int)

func SleepForMs

func SleepForMs(n int)

sleep for n milliseconds

func VerifyChecksum

func VerifyChecksum(data []byte, srcAddr, dstAddr net.Addr, protocolId uint8) bool

Types

type Connection

type Connection struct {
	NextSequenceNumber             uint32          // the SEQ sequence number of the next outgoing packet
	LastAckNumber                  uint32          // the last acknowleged incoming packet
	WindowSize                     uint16          // PCP windows size
	InitialSeq                     uint32          // connection's initial SEQ
	InitialPeerSeq                 uint32          // the initial SEQ from Peer
	TermStartSeq, TermStartPeerSeq uint32          // Seq and Peer Seq when 4-way termination starts
	InputChannel                   chan *PcpPacket // per connection packet input channel
	ReadChannel                    chan *PcpPacket // for connection read function
	ReadDeadline                   time.Time       // ReadDeadline for non-blocking read
	TerminationCallerState         uint            // 4-way termination caller states
	TerminationRespState           uint            // 4-way termination responder states
	InitClientState                uint            // 3-way handshake state of the client
	InitServerState                uint            // 3-way handshake state of the Server
	ConnSignalTimer                *time.Timer     // Timer for 3-way handshake and 4-way connection close
	ConnSignalRetryCount           int             // retry count for 3-way handshake and 4-way connection close
	TcpOptions                     *Options        // tcp options
	WriteOnHold                    bool            // true if 4-way termination starts
	IsOpenConnection               bool            //false if in 3-way handshake
	IsBidirectional                bool            // already seen normal packets from peer
	KeepaliveTimer                 *time.Timer     // Timer for keepalive mechanism
	KeepaliveTimerMutex            sync.Mutex      // mutex for KeepaliveTimer
	IdleTimeout                    time.Duration   // Idle timeout duration
	TimeoutCount                   int             // Timeout count for keepalive
	KeepaliveInterval              time.Duration   // Interval between keepalive attempts
	IsKeepAliveInProgress          bool            // denote if keepalive probe is in process or not
	IsDead                         bool            // mark the connection is idle timed out and failed keepalive probe
	ResendPackets                  ResendPackets   // data structure to hold sent packets which are not acknowledged yet
	ResendInterval                 time.Duration   // packet resend interval

	RevPacketCache PacketGapMap // Cache for received packets who has gap before it due to packet loss or out-of-order
	IsClosed       bool         // denote that the conneciton is closed so that no packets should be accepted

	ConnSignalFailed chan struct{}  // used to notify Connection signalling process (3-way handshake and 4-way termination) failed
	Wg               sync.WaitGroup // wait group for go routine

	Params *ConnectionParams // connection parameters
	// contains filtered or unexported fields
}

func NewConnection

func NewConnection(connParams *ConnectionParams, connConfig *ConnectionConfig) (*Connection, error)

func (*Connection) ClearConnResource

func (c *Connection) ClearConnResource()

clear connection resources and send close signal to paranet

func (*Connection) Close

func (c *Connection) Close() error

func (*Connection) CloseForcefully

func (c *Connection) CloseForcefully(wg *sync.WaitGroup) error

func (*Connection) Handle3WayHandshake

func (c *Connection) Handle3WayHandshake()

Server only. Handle ACK packet from client during the 3-way handshake.

func (*Connection) HandleIncomingPackets

func (c *Connection) HandleIncomingPackets()

func (*Connection) InitSendAck

func (c *Connection) InitSendAck()

func (*Connection) InitSendSyn

func (c *Connection) InitSendSyn()

func (*Connection) InitSendSynAck

func (c *Connection) InitSendSynAck()

func (*Connection) Read

func (c *Connection) Read(buffer []byte) (int, error)

func (*Connection) SetReadDeadline

func (c *Connection) SetReadDeadline(t time.Time) error

func (*Connection) StartConnSignalTimer

func (c *Connection) StartConnSignalTimer()

start Connection Signal timer to resend signal messages in 3-way handshake and 4-way termination

func (*Connection) StartResendTimer

func (c *Connection) StartResendTimer()

Method to start the resend timer

func (*Connection) StopConnSignalTimer

func (c *Connection) StopConnSignalTimer()

func (*Connection) TermCallerSendAck

func (c *Connection) TermCallerSendAck()

func (*Connection) TermCallerSendFin

func (c *Connection) TermCallerSendFin()

func (*Connection) TermRespSendFinAck

func (c *Connection) TermRespSendFinAck()

func (*Connection) UpdateACKAndSACK

func (c *Connection) UpdateACKAndSACK(packet *PcpPacket) (uint32, []SACKBlock)

func (*Connection) UpdateResendPacketsOnAck

func (c *Connection) UpdateResendPacketsOnAck(packet *PcpPacket)

func (*Connection) Write

func (c *Connection) Write(buffer []byte) (int, error)

type ConnectionConfig

type ConnectionConfig struct {
	WindowScale             int
	PreferredMSS            int
	SackPermitSupport       bool
	SackOptionSupport       bool
	IdleTimeout             int
	KeepAliveEnabled        bool
	KeepaliveInterval       int
	MaxKeepaliveAttempts    int
	ResendInterval          int
	MaxResendCount          int
	Debug                   bool // whether debug mode is on
	WindowSizeWithScale     int
	ConnSignalRetryInterval int
	ConnSignalRetry         int
}

connection config - see config file for detailed explanation

type ConnectionParams

type ConnectionParams struct {
	Key                      string           // connection key for easy reference
	IsServer                 bool             // server or client role
	RemoteAddr, LocalAddr    net.Addr         // IP addresses
	RemotePort, LocalPort    int              // port number
	OutputChan               chan *PcpPacket  // overall output channel shared by all connections
	SigOutputChan            chan *PcpPacket  // overall connection signalling output channel shared by all connections
	ConnCloseSignalChan      chan *Connection // send close connection signal to parent service or pConnection to clear it
	NewConnChannel           chan *Connection // server only. send new connection signal to parent service to signal successful 3-way handshake
	ConnSignalFailedToParent chan *Connection // used to send signal to parrent to notify connection establishment failed
}

type Options

type Options struct {
	WindowScaleShiftCount uint8  // TCP Window scaling, < 14 which mean WindowSize * 2^14
	MSS                   uint16 // max tcp segment size
	PermitSack            bool   // SACK permit support. No real support because no retransmission happens
	SackEnabled           bool   // enable SACK option kind 5 or not
	TimestampEnabled      bool   // timestamp support
	TsEchoReplyValue      uint32
	Timestamp             uint32
	InSACKOption          SACKOption // option kind 5 for incoming packets
	OutSACKOption         SACKOption // option kind 5 for outgoing packets
}

type PacketGapMap

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

func NewPacketGapMap

func NewPacketGapMap() *PacketGapMap

func (*PacketGapMap) AddPacket

func (pgm *PacketGapMap) AddPacket(packet *PcpPacket)

func (*PacketGapMap) GetPacket

func (pgm *PacketGapMap) GetPacket(seqNum uint32) (*ReceivedPacket, bool)

func (*PacketGapMap) RemovePacket

func (pgm *PacketGapMap) RemovePacket(seqNum uint32)

type PacketInfo

type PacketInfo struct {
	LastSentTime time.Time // Time the packet was last sent
	ResendCount  int       // Number of times the packet has been resent
	Data         *PcpPacket
}

PacketInfo represents information about a sent packet

type Payload

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

PayloadBytes represents packet payload byte slice

func (*Payload) Copy

func (p *Payload) Copy(src []byte) error

func (*Payload) GetSlice

func (p *Payload) GetSlice() []byte

func (*Payload) PrintContent

func (p *Payload) PrintContent()

PrintContent prints the content of the payload

func (*Payload) Reset

func (p *Payload) Reset()

Reset resets the content of the payload

func (*Payload) SetContent

func (p *Payload) SetContent(s string)

set the content of the payload

type PcpCore

type PcpCore struct {
	ProtocolID         uint8
	ProtoConnectionMap map[string]*PcpProtocolConnection // keep track of all protocolConn created by dialIP
	// contains filtered or unexported fields
}

func NewPcpCore

func NewPcpCore(pcpcoreConfig *PcpCoreConfig) (*PcpCore, error)

func (*PcpCore) Close

func (p *PcpCore) Close() error

func (*PcpCore) DialPcp

func (p *PcpCore) DialPcp(localIP string, serverIP string, serverPort uint16, pcpConfig *PcpProtocolConnConfig) (*Connection, error)

dialPcp simulates the TCP dial function interface for PCP.

func (*PcpCore) ListenPcp

func (p *PcpCore) ListenPcp(serviceIP string, port int, pcpConfig *PcpProtocolConnConfig) (*Service, error)

ListenPcp starts listening for incoming packets on the service's port.

type PcpCoreConfig

type PcpCoreConfig struct {
	ProtocolID      uint8 // protocol id which should be 6
	PayloadPoolSize int   // how many number of packet payload chunks in the pool
	PreferredMSS    int   // preferred MSS
}

type PcpPacket

type PcpPacket struct {
	SrcAddr, DestAddr net.Addr
	SourcePort        uint16 // SourcePort represents the source port
	DestinationPort   uint16 // DestinationPort represents the destination port
	SequenceNumber    uint32 // SequenceNumber represents the sequence number
	AcknowledgmentNum uint32 // AcknowledgmentNum represents the acknowledgment number
	WindowSize        uint16 // WindowSize specifies the number of bytes the receiver is willing to receive
	Flags             uint8  // Flags represent various control flags
	UrgentPointer     uint16 // UrgentPointer indicates the end of the urgent data (empty for now)
	Checksum          uint16 // Checksum is the checksum of the packet
	Payload           []byte // Payload represents the payload data
	TcpOptions        *Options
	IsOpenConnection  bool        // only used in outgoing packet to denote if the connection is open or in 3-way handshake stage
	Conn              *Connection // used for outgoing packets only to denote which connection it belongs to

	IsKeepAliveMassege bool // denote if this is a keepalive massage. If yes, don't put it into Connection's ResendPackets
	// contains filtered or unexported fields
}

PcpPacket represents a packet in your custom protocol

func NewPcpPacket

func NewPcpPacket(seqNum, ackNum uint32, flags uint8, data []byte, conn *Connection) *PcpPacket

func (*PcpPacket) CopyToPayload

func (p *PcpPacket) CopyToPayload(src []byte) error

func (*PcpPacket) GetChunk

func (p *PcpPacket) GetChunk()

func (*PcpPacket) GetChunkReference

func (p *PcpPacket) GetChunkReference() *rp.Element

func (*PcpPacket) Marshal

func (p *PcpPacket) Marshal(protocolId uint8, buffer []byte) (int, error)

Marshal converts a PcpPacket to a byte slice

func (*PcpPacket) ReturnChunk

func (p *PcpPacket) ReturnChunk()

func (*PcpPacket) Unmarshal

func (p *PcpPacket) Unmarshal(data []byte, srcAddr, destAddr net.Addr) error

Unmarshal converts a byte slice to a PcpPacket

type PcpProtocolConnConfig

type PcpProtocolConnConfig struct {
	IptableRuleDaley                 int
	PreferredMSS                     int
	PacketLostSimulation             bool
	PConnTimeout                     int
	ClientPortUpper, ClientPortLower int
	ConnConfig                       *ConnectionConfig
}

type PcpProtocolConnection

type PcpProtocolConnection struct {
	Key string // PCP protocol connection's key

	ServerAddr, LocalAddr *net.IPAddr            // server and local ip address
	ClientConn            *net.IPConn            // used for client side only
	ServerConn            net.PacketConn         // used for server side only
	OutputChan            chan *PcpPacket        // output channel for normal packets and signalling packets respectively
	ConnectionMap         map[string]*Connection // used for client side only

	ConnCloseSignal chan *Connection // receiving close signal from pcp connection. used for client side only
	ServiceMap      map[int]*Service // used for server side only
	// contains filtered or unexported fields
}

pcp protocol connection struct

func (*PcpProtocolConnection) Close

func (p *PcpProtocolConnection) Close()

Function to close the connection gracefully

type ReceivedPacket

type ReceivedPacket struct {
	ReceivedTime time.Time // Time the packet was last sent
	Packet       *PcpPacket
}

func NewReceivedPacket

func NewReceivedPacket(packet *PcpPacket) *ReceivedPacket

type ResendPackets

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

func NewResendPackets

func NewResendPackets() *ResendPackets

func (*ResendPackets) AddSentPacket

func (r *ResendPackets) AddSentPacket(packet *PcpPacket)

Function to add a sent packet to the map

func (*ResendPackets) GetPacketKeys

func (r *ResendPackets) GetPacketKeys() []uint32

func (*ResendPackets) GetSentPacket

func (r *ResendPackets) GetSentPacket(seqNum uint32) (*PacketInfo, bool)

Function to update information about a sent packet

func (*ResendPackets) RemovalLock

func (r *ResendPackets) RemovalLock()

func (*ResendPackets) RemovalUnlock

func (r *ResendPackets) RemovalUnlock()

func (*ResendPackets) RemoveSentPacket

func (r *ResendPackets) RemoveSentPacket(seqNum uint32)

Function to remove a sent packet from the map

func (*ResendPackets) UpdateSentPacket

func (r *ResendPackets) UpdateSentPacket(seqNum uint32) error

Function to update information about a sent packet

type SACKBlock

type SACKBlock struct {
	LeftEdge  uint32 // Left edge of the SACK block
	RightEdge uint32 // Right edge of the SACK block
}

type SACKOption

type SACKOption struct {
	Blocks []SACKBlock // Slice of SACK blocks
}

type Service

type Service struct {
	ServiceAddr  net.Addr
	Port         int
	InputChannel chan *PcpPacket // channel for incoming packets of the whole services (including packets for all connections)
	OutputChan   chan *PcpPacket // output channels for ordinary outgoing packets and priority signalling packets

	ConnCloseSignal chan *Connection // signal for connection close

	IsClosed bool // used to denote that the service is close so parent PCP Protocol connection won't forward more packets to it
	// contains filtered or unexported fields
}

Service represents a service listening on a specific port.

func (*Service) Accept

func (s *Service) Accept() (*Connection, error)

Accept accepts incoming connection requests.

func (*Service) Close

func (s *Service) Close() error

type TimeoutError

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

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

func (*TimeoutError) Temporary

func (e *TimeoutError) Temporary() bool

func (*TimeoutError) Timeout

func (e *TimeoutError) Timeout() bool

Jump to

Keyboard shortcuts

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