sctp

package module
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2025 License: MIT Imports: 16 Imported by: 0

README

SCTP for Go

Go Tests Go Reference codecov Fork me on GitHub

go-sctp is a Golang package that provides an efficient interface for working with the Stream Control Transmission Protocol (SCTP). SCTP support in the Go ecosystem has been sparse and go-sctp aims to fill this gap. It offers high-level abstractions like SCTPConn, SCTPListener, and SCTPAddr, seamlessly integrating with Go's net package by implementing net.Conn, net.Listener, and net.Addr. Also, it integrates with Go's runtime network poller to provide asynchronous low-level I/O and deadline support.

This library supports SCTP's one-to-one mode and is designed specifically for Linux environments. It mimics most of the TCP functionality implemented in Go's net package, with added support for multihoming, multistreaming and SCTP notifications.

go-sctp interfaces directly with the kernel SCTP module, leveraging system calls provided by Go's unix and syscall packages. This eliminates the need for external SCTP libraries, ensuring a lightweight, efficient, and dependency-free implementation.

Well-structured and comprehensive documentation is prioritized as part of the development process.


Features

  • Support for one-to-one SCTP mode (SOCK_STREAM socket type)
  • Use of non-blocking sockets
  • Integration with go's runtime network poller through os.File
  • Dial, Listen, Accept functionality following Go's TCP implementation logic
  • Basic SCTP read and write through SCTPConn.Read and SCTPConn.Write
  • Enhanced SCTP read and write through SCTPConn.ReadMsg and SCTPConn.WriteMsg
  • Deadline support for read/write/accept operations
  • Multi-streaming support through sctp.SndInfo and sctp.RcvInfo structures
  • Multi-homing support embedded in SCTPAddr
  • SCTP Notifications support
  • Exported socket options (i.e. SCTP_ADAPTATION_LAYER, SCTP_DISABLE_FRAGMENTS)
  • Runtime re-binding support through BindAdd and BindRemove
  • Shutdown and Abort support
  • Most of the TCP tests in Go's net package applied here to SCTP
  • Well documented

For a complete list of features and the history of changes introduced in each version, refer to the CHANGELOG.md.


Getting

go get -u github.com/georgeyanev/go-sctp


Usage

Most functionality mirrors Go's TCP implementation, making it intuitive to use. For example:

Dial:
conn, err := sctp.Dial("sctp4", "127.0.0.1/127.0.0.2:3868")
Listen:
ln, err := sctp.Listen("sctp4", "127.0.0.1/127.0.0.2:3868")
Accept:
conn, err := ln.Accept()
Kernel parameters:

For optimal performance set the kernel parameters net.core.rmem_max and net.core.wmem_max to at least 512KB


Contributing

Contributions are welcome! If you find a bug, have a feature request, or want to contribute code, feel free to open an issue or pull request.

Documentation

Index

Constants

View Source
const (
	SCTP_ASSOC_CHANGE
	SCTP_PEER_ADDR_CHANGE

	SCTP_REMOTE_ERROR
	SCTP_SHUTDOWN_EVENT
	SCTP_PARTIAL_DELIVERY_EVENT // no parsing due to discrepancies between sctp.h and RFC6458
	SCTP_ADAPTATION_INDICATION
	SCTP_AUTHENTICATION_EVENT
	SCTP_SENDER_DRY_EVENT
	SCTP_STREAM_RESET_EVENT
	SCTP_ASSOC_RESET_EVENT
	SCTP_STREAM_CHANGE_EVENT
	SCTP_SEND_FAILED_EVENT
)

event types

View Source
const (
	// SCTP_COMM_UP shows that a new association is now ready, and data may be
	// exchanged with this peer.  When an association has been
	// established successfully, this notification should be the first one.
	SCTP_COMM_UP = iota

	// SCTP_COMM_LOST shows that the association has failed.  The association is
	// now in the closed state.  If SEND_FAILED notifications are
	// turned on, an SCTP_COMM_LOST is accompanied by a series of
	// SCTP_SEND_FAILED_EVENT events, one for each outstanding message.
	SCTP_COMM_LOST

	// SCTP_RESTART shows that the peer has restarted.
	SCTP_RESTART

	// SCTP_SHUTDOWN_COMP means the association has gracefully closed.
	SCTP_SHUTDOWN_COMP

	// SCTP_CANT_STR_ASSOC shows that the association setup failed.
	SCTP_CANT_STR_ASSOC
)

SCTP_ASSOC_CHANGE state

View Source
const (
	// SCTP_ADDR_AVAILABLE shows that this address is now reachable.  This
	// notification is provided whenever an address becomes reachable.
	SCTP_ADDR_AVAILABLE = iota

	// SCTP_ADDR_UNREACHABLE shows that the address specified can no longer be
	// reached.  Any data sent to this address is rerouted to an
	// alternate until this address becomes reachable.  This
	// notification is provided whenever an address becomes
	// unreachable.
	SCTP_ADDR_UNREACHABLE

	// SCTP_ADDR_REMOVED shows that the address is no longer part of the association.
	SCTP_ADDR_REMOVED

	// SCTP_ADDR_ADDED shows that the address is now part of the association.
	SCTP_ADDR_ADDED

	// SCTP_ADDR_MADE_PRIM shows that this address has now been made the primary
	// destination address.  This notification is provided whenever an
	// address is made primary.
	SCTP_ADDR_MADE_PRIM

	SCTP_ADDR_CONFIRMED
	SCTP_ADDR_POTENTIALLY_FAILED
)

SCTP_PEER_ADDR_CHANGE state

View Source
const (
	// SCTP_DATA_UNSENT indicates that the data was never put on the wire
	SCTP_DATA_UNSENT = 0

	// SCTP_DATA_SENT indicates that the data was put on the wire.
	// Note that this does not necessarily mean that the data
	// was (or was not) successfully delivered.
	SCTP_DATA_SENT = 1
)

SendFailedEvent flags

View Source
const (
	SCTP_DATA_LAST_FRAG = 1
	SCTP_DATA_NOT_FRAG  = 3
)

SfeSndInfo flags

View Source
const (
	// SCTP_NOTIFICATION indicates that the received message is
	// an SCTP event and not a data message.
	SCTP_NOTIFICATION = 0x8000

	// SCTP_EOR indicates the end of a message (End Of Record).
	// See SCTPConn.ReadMsgExt for more details
	SCTP_EOR = 0x80 // unix.MSG_EOR

	// SCTP_CTRUNC indicates the ancillary data was truncated.
	// See SCTPConn.ReadMsgExt for more details
	SCTP_CTRUNC = 0x8 // unix.MSG_CTRUNC
)

flags set upon calling ReadMsg in recvFlags

View Source
const (
	// SCTP_UNORDERED flag requests the unordered delivery of the
	// message.  If this flag is clear, the datagram is considered an
	// ordered send.
	SCTP_UNORDERED = 1

	// SCTP_ADDR_OVER is filled automatically by WriteMsg function,
	// when a 'to' address is specified
	SCTP_ADDR_OVER = 2

	// SCTP_ABORT causes the specified association to
	// abort by sending an ABORT message to the peer.  The ABORT chunk
	// will contain an error cause of 'User Initiated Abort' with
	// cause code 12.  The cause-specific information of this error
	// cause is provided in the byte buffer passed in.
	SCTP_ABORT = 4

	// SCTP_SENDALL has no effect for the one-to-one style socket
	SCTP_SENDALL = 64

	// SCTP_EOF invokes the SCTP graceful shutdown
	// procedures on the specified association.  Graceful shutdown
	// assures that all data queued by both endpoints is successfully
	// transmitted before closing the association.
	SCTP_EOF = 0x200 // unix.MSG_FIN
)

SndInfo flags

View Source
const (
	SCTP_EMPTY             = 0
	SCTP_CLOSED            = 1
	SCTP_COOKIE_WAIT       = 2
	SCTP_COOKIE_ECHOED     = 3
	SCTP_ESTABLISHED       = 4
	SCTP_SHUTDOWN_PENDING  = 5
	SCTP_SHUTDOWN_SENT     = 6
	SCTP_SHUTDOWN_RECEIVED = 7
	SCTP_SHUTDOWN_ACK_SENT = 8
)

Status state values

View Source
const (
	// SCTP_UNCONFIRMED is the initial state of a peer address.
	SCTP_UNCONFIRMED = 3

	// SCTP_ACTIVE state is entered the first time after path
	// verification.  It can also be entered if the state is
	// SCTP_INACTIVE and the path supervision detects that the peer
	// address is reachable again.
	SCTP_ACTIVE = 2

	// SCTP_INACTIVE state is entered whenever a path failure is detected.
	SCTP_INACTIVE = 0
)

PeerAddrInfo state values

Variables

View Source
var (
	ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection")
)

Functions

func Dial

func Dial(network, address string) (net.Conn, error)

Dial connects to the address on the named network.

Known networks are "sctp", "sctp4" (IPv4-only), "sctp6" (IPv6-only),

The address has the form "host:port" for single-homing or host1/host2/host3:port for multi-homing (the number of hosts/IPs are not limited) The host must be a literal IP address, or a host name that can be resolved to IP addresses (which is not recommended, because at most one of the host's IP addresses will be used). The port must be a literal port number or a service name. If the host is a literal IPv6 address it must be enclosed in square brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80". The zone specifies the scope of the literal IPv6 address as defined in RFC 4007.

Examples:

Dial("sctp", "golang.org:http")
Dial("sctp", "192.0.2.1/192.0.2.2:http")
Dial("sctp", "198.51.100.1/[2001:db8::1]:8000")
Dial("sctp", "[fe80::1%lo0]/[::1]:5333")
Dial("sctp", ":8000")

If the host is empty or a literal unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" the local system is assumed.

func Htonui16

func Htonui16(i uint16) uint16

Htonui16 does host to network byte order for an uint16

func Htonui32

func Htonui32(i uint32) uint32

Htonui32 does host to network byte order for an uint32

func Listen

func Listen(network, address string) (net.Listener, error)

Listen announces on the local network address.

The network must be "sctp", "sctp4" or "sctp6".

If the host in the address parameter is empty or a literal unspecified IP address, Listen listens on all available IP addresses of the local system. To only use IPv4, use network "sctp4". The address can use a host name, but this is not recommended, because it will create a listener for at most one of the host's IP addresses. If the port in the address parameter is empty or "0", as in "127.0.0.1:" or "[::1]:0", a port number is automatically chosen. The [Addr] method of [Listener] can be used to discover the chosen port. Multiple addresses can be specified separated by '/' as in : 127.0.0.1/127.0.0.2:0 (sctp4 network) [::1]/[::2]:0 (sctp6 network) [::1]/127.0.0.1:0 (sctp network) For an extensive list of possibilities consult listen_test.go

Listen uses context.Background internally; to specify the context, use ListenConfig.Listen.

func Ntohui16

func Ntohui16(i uint16) uint16

Ntohui16 does network to host byte order for an uint16

func Ntohui32

func Ntohui32(i uint32) uint32

Ntohui32 does network to host byte order for an uint32

Types

type AdaptationEvent

type AdaptationEvent struct {
	// This field holds the bit array sent by the peer
	// in the Adaptation Layer Indication parameter
	AdaptationInd uint32

	// Association Id is ignored in one-to-one mode
	AssocId int32
}

AdaptationEvent is delivered by SCTP to inform the application about the peer's adaptation layer indication (When a peer sends an Adaptation Layer Indication parameter as described in RFC5061)

func (*AdaptationEvent) Flags

func (*AdaptationEvent) Flags() int

Flags is ignored for this event

func (*AdaptationEvent) Type

func (*AdaptationEvent) Type() EventType

type AssocChangeEvent

type AssocChangeEvent struct {
	// One of SCTP_ASSOC_CHANGE states
	State uint16

	// If the state was reached due to an error condition (e.g.,
	// SCTP_COMM_LOST), any relevant error information is available in
	// this field.  This corresponds to the protocol error codes defined
	// in [RFC4960].
	Error uint16

	// Maximum number of outbound streams
	OutboundStreams uint16

	// Maximum number of inbound streams
	InboundStreams uint16

	// Association Id is ignored in one-to-one mode
	AssocId int32

	// Additional information. See [RFC6458]#section-6.1.1
	Info []byte
}

AssocChangeEvent informs the application that an SCTP association has either started or ended.

func (*AssocChangeEvent) Flags

func (*AssocChangeEvent) Flags() int

Flags is ignored for this event

func (*AssocChangeEvent) Type

func (*AssocChangeEvent) Type() EventType

type Dialer

type Dialer struct {
	// Timeout is the maximum amount of time a dial will wait for
	// a connect to complete. If Deadline is also set, it may fail
	// earlier.
	//
	// The default is no timeout.
	//
	// With or without a timeout, the operating system may impose
	// its own earlier timeout.
	Timeout time.Duration

	// Deadline is the absolute point in time after which dials
	// will fail. If Timeout is set, it may fail earlier.
	// Zero means no deadline, or dependent on the operating system
	// as with the Timeout option.
	Deadline time.Time

	// LocalAddr is the local address to use when dialing an address.
	// If nil, a local address is automatically chosen.
	LocalAddr *SCTPAddr

	// If Control is not nil, it is called after creating the network
	// connection but before actually dialing.
	//
	// Network and address parameters passed to Control function are not
	// necessarily the ones passed to Dial. For example, passing "sctp" to Dial
	// will cause the Control function to be called with "sctp4" or "sctp6".
	//
	// Control is ignored if ControlContext is not nil.
	Control func(network, address string, c syscall.RawConn) error

	// If ControlContext is not nil, it is called after creating the network
	// connection but before actually dialing.
	//
	// Network and address parameters passed to ControlContext function are not
	// necessarily the ones passed to Dial. For example, passing "sctp" to Dial
	// will cause the ControlContext function to be called with "sctp4" or "sctp6".
	//
	// If ControlContext is not nil, Control is ignored.
	ControlContext func(ctx context.Context, network, address string, c syscall.RawConn) error

	// provides information for initializing new SCTP associations
	InitOptions InitOptions
}

A Dialer contains options for connecting to an address.

func (*Dialer) Dial

func (d *Dialer) Dial(network, address string) (net.Conn, error)

Dial connects to the address on the named network.

See func Dial for a description of the network and address parameters.

Dial uses context.Background internally; to specify the context, use Dialer.DialContext.

func (*Dialer) DialContext

func (d *Dialer) DialContext(ctx context.Context, network string, address string) (net.Conn, error)

DialContext connects to the address on the named network using the provided context. The context is not used in resolving host to IP addresses (if there is any).

The provided Context must be non-nil. If the context expires before the connection is complete, an error is returned. Once successfully connected, any expiration of the context will not affect the connection.

func (*Dialer) DialSCTP

func (d *Dialer) DialSCTP(network string, raddr *SCTPAddr) (*SCTPConn, error)

func (*Dialer) DialSCTPContext

func (d *Dialer) DialSCTPContext(ctx context.Context, network string, raddr *SCTPAddr) (*SCTPConn, error)

DialSCTPContext acts like DialContext taking SCTP addresses and returning a SCTPConn.

type Event

type Event interface {
	Type() EventType
	Flags() int
}

func ParseEvent

func ParseEvent(b []byte) (Event, error)

ParseEvent parses an SCTP event from a byte slice

type EventType

type EventType int

type InitOptions

type InitOptions struct {
	// Number of streams to which the application wishes to be able to send, 10 by default
	NumOstreams uint16
	// Maximum number of inbound streams the application is prepared to support, 10 by default
	MaxInstreams uint16
	// How many attempts the SCTP endpoint should make at resending the INIT
	// if not specified the kernel parameter net.sctp.max_init_retransmits is used as default
	MaxAttempts uint16
	// Largest timeout or retransmission timeout (RTO) value (in milliseconds) to use in attempting an INIT
	// if not specified the kernel parameter net.sctp.rto_max is used as default
	MaxInitTimeout uint16

	// Default value for read and write buffers is 512K (usually the linux kernel doubles this value)
	// Note that buffer sizes are limited by the kernel parameters `net.core.rmem_max` and `net.core.wmem_max`
	// unless we run as a privileged user
	SocketReadBufferSize  int
	SocketWriteBufferSize int

	// This option requests that the local endpoint set the specified
	// Adaptation Layer Indication parameter. If the value is `true`
	// the Adaptation Layer Indication parameter is set to the value
	// specified in the AdaptationIndication field.
	AdaptationIndicationEnabled bool
	AdaptationIndication        uint32
}

InitOptions structure provides information for initializing new SCTP associations

type ListenConfig

type ListenConfig struct {
	// If Control is not nil, it is called after creating the network
	// connection but before binding it to the operating system.
	//
	// Network and address parameters passed to Control method are not
	// necessarily the ones passed to Listen. For example, passing "sctp" to
	// Listen will cause the Control function to be called with "sctp4" or "sctp6".
	Control func(network, address string, c syscall.RawConn) error

	// provides information for initializing new SCTP associations
	InitOptions InitOptions
}

ListenConfig contains options for listening to an address.

func (*ListenConfig) Listen

func (lc *ListenConfig) Listen(network, address string) (net.Listener, error)

func (*ListenConfig) ListenSCTP

func (lc *ListenConfig) ListenSCTP(network string, laddr *SCTPAddr) (*SCTPListener, error)

type PeerAddrChangeEvent

type PeerAddrChangeEvent struct {
	// The affected address field holds the remote peer's
	// address that is encountering the change of state
	Addr net.IPAddr

	// One of SCTP_PEER_ADDR_CHANGE states
	State uint32

	// If the state was reached due to any error condition
	// (e.g., SCTP_ADDR_UNREACHABLE), any relevant error information is
	// available in this field
	Error uint32

	// Association Id is ignored in one-to-one mode
	AssocId int32
}

PeerAddrChangeEvent is sent When a destination address of a multi-homed peer encounters a state change. Reception of PeerAddrChangeEvent when the peer adds or removes addresses to/from the association is affected by `net.sctp.addip_enable` and `net.sctp.addip_noauth_enable` kernel parameters.

func (*PeerAddrChangeEvent) Flags

func (*PeerAddrChangeEvent) Flags() int

Flags is ignored for this event

func (*PeerAddrChangeEvent) Type

type PeerAddrInfo

type PeerAddrInfo struct {
	// Association Id is ignored in one-to-one mode
	AssocId int32

	// This is filled by the application and contains the
	// peer address of interest.
	Addr *SCTPAddr

	// Contains the peer address's state. See PeerAddrInfo state values
	State int32

	// Contains the peer address's current congestion window.
	Cwnd uint32

	// Contains the peer address's current smoothed
	// round-trip time calculation in milliseconds.
	Srtt uint32

	// Contains the peer address's current retransmission
	// timeout value in milliseconds.
	Rto uint32

	// Contains the current Path MTU of the peer address.  It is
	// the number of bytes available in an SCTP packet for chunks.
	Mtu uint32
}

PeerAddrInfo contains information about a specific peer address of an association, including its reachability state, congestion window, and retransmission timer values.

type RcvInfo

type RcvInfo struct {
	// The SCTP stack places the message's stream number in this value.
	Sid uint16

	// This value contains the stream sequence number that the
	// remote endpoint placed in the DATA chunk.  For fragmented
	// messages, this is the same number for all deliveries of the
	// message (if more than one recvmsg() is needed to read the message).
	Ssn uint16

	// This field may contain any of the following flags and is
	// composed of a bitwise OR of these values:
	//
	// SCTP_UNORDERED:  This flag is present when the message was sent unordered.
	Flags uint16

	// Payload protocol identifier
	Ppid uint32

	// TSN that was assigned to one of the SCTP DATA chunks
	Tsn uint32

	// Current cumulative TSN as known by the underlying SCTP layer.
	Cumtsn uint32

	// This value is an opaque 32-bit context datum that was
	// set by the user with the SCTP_CONTEXT socket option.  This value
	// is passed back to the upper layer if an error occurs on the send
	// of a message and is retrieved with each undelivered message.
	Context uint32

	// Association Id is ignored in one-to-one mode
	AssocId int32
	// contains filtered or unexported fields
}

RcvInfo structure describes SCTP receive information about a received message RcvInfo is returned by SCTPConn.ReadMsg function

type RemoteErrorEvent

type RemoteErrorEvent struct {
	Error uint16

	// Association Id is ignored in one-to-one mode
	AssocId int32

	// This contains the ERROR chunk as defined in Section 3.3.10
	// of the SCTP specification [RFC4960].
	Data []byte
}

func (*RemoteErrorEvent) Flags

func (*RemoteErrorEvent) Flags() int

Flags is ignored for this event

func (*RemoteErrorEvent) Type

func (*RemoteErrorEvent) Type() EventType

type SCTPAddr

type SCTPAddr struct {
	IPAddrs []net.IPAddr
	Port    int
}

SCTPAddr represents the address of an SCTP endpoint. It contains an address array because of the multi-homing feature of SCTP

func ResolveSCTPAddr

func ResolveSCTPAddr(network, addr string) (*SCTPAddr, error)

ResolveSCTPAddr returns an address of an SCTP end point. The network must be an SCTP network name. See func Dial for a description of the network and address parameters.

func (*SCTPAddr) Network

func (a *SCTPAddr) Network() string

func (*SCTPAddr) String

func (a *SCTPAddr) String() string

type SCTPConn

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

func DialSCTP

func DialSCTP(network string, laddr, raddr *SCTPAddr) (*SCTPConn, error)

DialSCTP acts like Dial taking SCTP addresses and returning a SCTPConn.

If laddr is nil, a local address is automatically chosen. If raddr is nil or an unspecified IP address, the local system is assumed.

func (*SCTPConn) BindAdd

func (c *SCTPConn) BindAdd(address string) error

BindAdd associates additional addresses with an already bound endpoint (i.e. socket). If the endpoint supports dynamic address reconfiguration, BindAdd may cause an endpoint to send the appropriate message to its peer to change the peer's address lists.

Port number should be absent from the address string.

The outcome of BindAdd and BindRemove is affected by `net.sctp.addip_enable` and `net.sctp.addip_noauth_enable` kernel parameters.

func (*SCTPConn) BindAddSCTP

func (c *SCTPConn) BindAddSCTP(laddr *SCTPAddr) error

func (*SCTPConn) BindRemove

func (c *SCTPConn) BindRemove(address string) error

BindRemove removes some addresses with which a bound socket is associated. If the endpoint supports dynamic address reconfiguration, BindRemove may cause an endpoint to send the appropriate message to its peer to change the peer's address lists.

Port number should be absent from the address string.

The outcome of BindAdd and BindRemove is affected by `net.sctp.addip_enable` and `net.sctp.addip_noauth_enable` kernel parameters.

func (*SCTPConn) BindRemoveSCTP

func (c *SCTPConn) BindRemoveSCTP(laddr *SCTPAddr) error

func (*SCTPConn) Close

func (c *SCTPConn) Close() error

Close closes the association. By default, a graceful close is performed and a SHUTDOWN message is sent to the peer. If different behaviour is desired (i.e. immediate close and sending ABORT chunk), use SCTPConn.SetLinger Also, different close behaviour can be achieved by using the SndInfo flags appropriately.

func (*SCTPConn) CloseRead

func (c *SCTPConn) CloseRead() error

CloseRead Disables further receive operations. No SCTP protocol action is taken. Most callers should just use Close.

After calling CloseWrite or CloseRead, Close should be called to close the socket descriptor.

func (*SCTPConn) CloseWrite

func (c *SCTPConn) CloseWrite() error

CloseWrite Disables further send operations, and initiates the SCTP shutdown sequence. Most callers should just use Close.

The major difference between SCTP and TCP shutdown() is that SCTP SHUT_WR (CloseWrite) initiates immediate and full protocol shutdown, whereas TCP SHUT_WR causes TCP to go into the half close state. SHUT_RD (CloseRead) behaves the same for SCTP as for TCP. The purpose of SCTP SHUT_WR is to close the SCTP association while still leaving the socket descriptor open. This allows the caller to receive back any data that SCTP is unable to deliver and receive event notifications. After calling CloseWrite or CloseRead, Close should be called to close the socket descriptor.

To perform the ABORT operation, an application can use the SetLinger function, or SCTP_ABORT flag in SndInfo struct.

func (*SCTPConn) LocalAddr

func (c *SCTPConn) LocalAddr() net.Addr

func (*SCTPConn) Read

func (c *SCTPConn) Read(b []byte) (int, error)

Read receives data from the peer of an SCTP endpoint. It gives access to only basic SCTP protocol features. If either peer in the association uses multiple streams, or sends unordered data, this call will usually be inadequate and may deliver the data in unpredictable ways. Read return data from any stream, but the caller cannot distinguish the different streams. This may result in data seeming to arrive out of order. Similarly, if a DATA chunk is sent unordered, Read() provide no indication. If the buffer supplied is not large enough to hold a complete SCTP message, the Read call acts like a stream socket and returns as much data as will fit in the buffer.

Read cannot distinguish message boundaries (i.e., there is no way to observe the MSG_EOR flag to detect partial delivery) Since os.File is used for integration with the poller, os.ErrClosed should be checked instead of net.ErrClosed.

If specific SCTP features are needed, SCTPConn.ReadMsg function can be used.

func (*SCTPConn) ReadBufferSize added in v0.11.0

func (c *SCTPConn) ReadBufferSize() (int, error)

ReadBufferSize returns the current socket's read buffer size in bytes.

func (*SCTPConn) ReadMsg

func (c *SCTPConn) ReadMsg(b []byte) (n int, rcvInfo *RcvInfo, recvFlags int, err error)

func (*SCTPConn) ReadMsgExt added in v0.11.0

func (c *SCTPConn) ReadMsgExt(b, oob []byte) (n int, rcvInfo *RcvInfo, recvFlags int, err error)

ReadMsgExt reads a message from the socket and stores it into 'b'. The 'obb' buffer is filled with ancillary data from which the rcvInfo return arg is composed.

If there is no room for the message in b, ReadMsgExt fills b with part of the message and clears SCTP_EOR flag in recvFlags. The rest of the message should be retrieved using subsequent calls to ReadMsgExt, the last one having SCTP_EOR set. If there is no room for the ancillary data in obb, ReadMsgExt fills obb with part of the ancillary data and sets SCTP_CTRUNC flag in recvFlags.

The message stored in 'b' can be a regular message or a notification(event) message. Notifications are returned only if Subscribe has been called prior to reading the message. If the message is a notification, the SCTP_NOTIFICATION flag will be set in recvFlags. A ReadMsgExt call will return only one notification at a time. Just as when reading normal data, it may return part of a notification if the buffer passed is not large enough. If a single read is not sufficient, recvFlags will have SCTP_EOR unset, indicating the need for further reads to complete the notification retrieval. The notification message can later be parsed with ParseEvent function once a complete message has been obtained.

ReadMsgExt returns:

n: Number of bytes read and stored into b. rcvInfo: Information about the received message. recvFlags: Received message flags (i.e. SCTP_NOTIFICATION, SCTP_EOR). err: Error encountered during reading, if any.

Since os.File is used for integration with the poller, os.ErrClosed should be checked instead of net.ErrClosed.

If the basic SCTP functionality meets the caller's needs, the SCTPConn.Read function may be used as a simpler alternative.

func (*SCTPConn) RefreshRemoteAddr

func (c *SCTPConn) RefreshRemoteAddr() (*SCTPAddr, error)

RefreshRemoteAddr is called to refresh potentially changed remote peer address. I.e. after receiving an SCTP_PEER_ADDR_CHANGE event

func (*SCTPConn) RemoteAddr

func (c *SCTPConn) RemoteAddr() net.Addr

func (*SCTPConn) SetDeadline

func (c *SCTPConn) SetDeadline(t time.Time) error

SetDeadline sets both the read and write deadlines associated with the Conn.

func (*SCTPConn) SetDisableFragments

func (c *SCTPConn) SetDisableFragments(disableFragments bool) error

SetDisableFragments turns an on/off flag. If enabled, no SCTP message fragmentation will be performed. The effect of enabling this option is that if a message being sent exceeds the current Path MTU (PMTU) size, the message will not be sent and instead an error will be indicated to the user. If this option is disabled (the default), then a message exceeding the size of the PMTU will be fragmented and reassembled by the peer.

func (*SCTPConn) SetLinger

func (c *SCTPConn) SetLinger(sec int) error

SetLinger sets the behavior of Close on a connection which still has data waiting to be sent or to be acknowledged.

If sec < 0 (the default), SCTP attempts to close the connection gracefully by sending a SHUTDOWN message and finish sending/acknowledging the data in the background.

If sec == 0, SCTP discards any unsent or unacknowledged data and sends an ABORT chunk.

If sec > 0, the data is sent in the background as with sec < 0. The Close() can be blocked for at most sec time. Note that the time unit is in seconds, according to POSIX, but might be different on specific platforms. If the graceful shutdown phase does not finish during this period, Close() will return, but the graceful shutdown phase will continue in the system.

func (*SCTPConn) SetNoDelay

func (c *SCTPConn) SetNoDelay(noDelay bool) error

SetNoDelay turns on/off any Nagle-like algorithm. This means that packets are generally sent as soon as possible, and no unnecessary delays are introduced, at the cost of more packets in the network. In particular, not using any Nagle-like algorithm might reduce the bundling of small user messages in cases where this would require an additional delay. Turning this option on disables any Nagle-like algorithm.

func (*SCTPConn) SetReadDeadline

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

SetReadDeadline sets the read deadline associated with the Conn.

func (*SCTPConn) SetWriteDeadline

func (c *SCTPConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline associated with the Conn.

func (*SCTPConn) Status

func (c *SCTPConn) Status() (*Status, error)

Status returns the current status of the SCTP association.

func (*SCTPConn) Subscribe

func (c *SCTPConn) Subscribe(event ...EventType) error

Subscribe to one or more of the SCTP event types. By default, we do not subscribe to any events. Once Subscribe is called, the events are received with ReadMsg having SCTP_NOTIFICATION flag set in recvFlags.

func (*SCTPConn) Unsubscribe

func (c *SCTPConn) Unsubscribe(event ...EventType) error

Unsubscribe from one or more of the SCTP event types we have previously subscribed.

func (*SCTPConn) Write

func (c *SCTPConn) Write(b []byte) (int, error)

Write transmit data to the peer of an SCTP endpoint. It gives access to only basic SCTP protocol features. SCTP has the concept of multiple streams in one association. Write do not allow the caller to specify on which stream a message should be sent. The system uses stream 0 as the default stream. SCTP is message based. The msg buffer passed in Write is considered to be a single message.

Sending a message using Write is atomic. The maximum size of the buffer passed to Write is limited by the write buffer size of the socket. See: https://datatracker.ietf.org/doc/html/rfc6458#page-67

Write return errors from `os` package so check for os.ErrClosed instead of net.ErrClosed for closure detection.

If specific SCTP features are needed, the SCTPConn.WriteMsg function can be used.

func (*SCTPConn) WriteBufferSize added in v0.11.0

func (c *SCTPConn) WriteBufferSize() (int, error)

WriteBufferSize returns the current socket's write buffer size in bytes.

func (*SCTPConn) WriteMsg

func (c *SCTPConn) WriteMsg(b []byte, info *SndInfo) (int, error)

WriteMsg is a simplified form of WriteMsgExt

func (*SCTPConn) WriteMsgExt

func (c *SCTPConn) WriteMsgExt(b []byte, info *SndInfo, to *net.IPAddr, flags int) (int, error)

WriteMsgExt is used to transmit the data passed in `b` to its peer. Different types of ancillary data can be sent and received along with user data. When sending, the ancillary data is used to specify the send behavior, such as the SCTP stream number to use or the protocol payload identifier (Ppid). These are specified in the SndInfo struct, which is optional. If SndInfo is null the data is sent on stream number 0 by default. If the caller wants to send the message to a specific peer address (hence overriding the primary address), it can provide the specific address in the `to` argument.

This function call may also be used to terminate an association. The caller provides an SndInfo struct with the Flags field set to SCTP_EOF.

WriteMsgExt returns the number of bytes accepted by the kernel or an error in case of any. Since os.File is used for integration with the poller, os.ErrClosed should be checked instead of net.ErrClosed for closure detection.

If the basic SCTP functionality meets the caller's needs, the SCTPConn.Write function may be used as a simpler alternative.

type SCTPListener

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

func ListenSCTP

func ListenSCTP(network string, laddr *SCTPAddr) (*SCTPListener, error)

ListenSCTP acts like Listen for SCTP networks.

If the IP field of laddr is nil or an unspecified IP address, ListenSCTP listens on all available IP addresses of the local system. If the Port field of laddr is 0, a port number is automatically chosen.

func (*SCTPListener) Accept

func (ln *SCTPListener) Accept() (net.Conn, error)

Accept implements the Accept method in the [Listener] interface; it waits for the next call and returns a generic [Conn].

func (*SCTPListener) AcceptSCTP

func (ln *SCTPListener) AcceptSCTP() (*SCTPConn, error)

AcceptSCTP accepts the next incoming call and returns the new connection.

func (*SCTPListener) Addr

func (ln *SCTPListener) Addr() net.Addr

Addr returns the listener's network address, a *SCTPAddr. The Addr returned is shared by all invocations of Addr, so do not modify it.

func (*SCTPListener) BindAdd

func (ln *SCTPListener) BindAdd(address string) error

BindAdd associates additional addresses with an already bound endpoint (i.e. socket). If the endpoint supports dynamic address reconfiguration, BindAdd may cause an endpoint to send the appropriate message to its peer to change the peer's address lists. New accepted associations will be associated with these addresses in addition to the already present ones.

Port number should be absent from the address string.

The outcome of BindAdd and BindRemove is affected by `net.sctp.addip_enable` and `net.sctp.addip_noauth_enable` kernel parameters.

func (*SCTPListener) BindAddSCTP

func (ln *SCTPListener) BindAddSCTP(laddr *SCTPAddr) error

func (*SCTPListener) BindRemove

func (ln *SCTPListener) BindRemove(address string) error

BindRemove remove some addresses with which a bound socket is associated. If the endpoint supports dynamic address reconfiguration, BindRemove may cause an endpoint to send the appropriate message to its peer to change the peer's address lists. New associations accepted will not be associated with these addresses.

Port number should be absent from the address string.

The outcome of BindAdd and BindRemove is affected by `net.sctp.addip_enable` and `net.sctp.addip_noauth_enable` kernel parameters.

func (*SCTPListener) BindRemoveSCTP

func (ln *SCTPListener) BindRemoveSCTP(laddr *SCTPAddr) error

func (*SCTPListener) Close

func (ln *SCTPListener) Close() error

Close stops listening on the SCTP address. Already Accepted connections are not closed.

func (*SCTPListener) SetDeadline

func (ln *SCTPListener) SetDeadline(t time.Time) error

SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.

func (*SCTPListener) Subscribe

func (ln *SCTPListener) Subscribe(event ...EventType) error

Subscribe to one or more of the SCTP event types. By default, we do not subscribe to any events. Once Subscribe is called, the events are received with ReadMsg having SCTP_NOTIFICATION flag set in recvFlags. The subscription is transferred to the new accepted connections.

func (*SCTPListener) Unsubscribe

func (ln *SCTPListener) Unsubscribe(event ...EventType) error

Unsubscribe from one or more of the SCTP event types we have previously subscribed.

type SendFailedEvent

type SendFailedEvent struct {
	// One of the flags defined in SendFailedEvent flags
	SfeFlags uint16

	// This value represents the reason why the send failed,
	// and if set, will be an SCTP protocol error code as defined in
	// Section 3.3.10 of RFC9260.
	Error uint32

	// This field includes the ancillary data (struct
	// SndInfo) used to send the undelivered message.  Regardless of
	// whether ancillary data is used or not, the SfeSndInfo.Flags
	// field indicates whether the complete message or only part of the
	// message is returned in Data.  If only part of the message is
	// returned, it means that the part that is not present has been sent
	// successfully to the peer.
	//
	// If the complete message cannot be sent, the SCTP_DATA_NOT_FRAG
	// flag is set in SfeSndInfo.Flags.  If the first part of the
	// message is sent successfully, SCTP_DATA_LAST_FRAG is set.  This
	// means that the tail end of the message is returned in ssf_data.
	SfeSndInfo SndInfo

	// Association Id is ignored in one-to-one mode
	AssocId int32

	// The undelivered message or part of the undelivered
	// message will be present in the ssf_data field. Note that the
	// SfeSndInfo.Flags field as noted above should be used to
	// determine whether a complete message or just a piece of the
	// message is present.  Note that only user data is present in this
	// field; any chunk headers or SCTP common headers must be removed by
	// the SCTP stack.
	Data []byte
}

func (*SendFailedEvent) Flags

func (sfe *SendFailedEvent) Flags() int

func (*SendFailedEvent) Type

func (*SendFailedEvent) Type() EventType

type SenderDryEvent

type SenderDryEvent struct {
	// Association Id is ignored in one-to-one mode
	AssocId int32
}

SenderDryEvent is received to inform the application that the stack has no more user data to send or retransmit. Also, at the time when a user app subscribes to this event, if there is no data to be sent or retransmit, the stack will immediately send up this notification.

func (*SenderDryEvent) Flags

func (sfe *SenderDryEvent) Flags() int

func (*SenderDryEvent) Type

func (*SenderDryEvent) Type() EventType

type ShutdownEvent

type ShutdownEvent struct {
	// Association Id is ignored in one-to-one mode
	AssocId int32
}

ShutdownEvent is received to inform the application that it should cease sending data.

func (*ShutdownEvent) Flags

func (*ShutdownEvent) Flags() int

Flags is ignored for this event

func (*ShutdownEvent) Type

func (*ShutdownEvent) Type() EventType

type SndInfo

type SndInfo struct {
	// Sid value holds the stream number to which the application
	// wishes to send this message.  If a sender specifies an invalid
	// stream number, an error indication is returned and the call fails
	Sid uint16

	// Flags field is composed of a bitwise OR of the values
	// defined in SndInfo flags
	Flags uint16

	// Payload protocol identifier
	Ppid uint32

	// This value is an opaque 32-bit context datum that is
	// used in WriteMsg() functions.  This value is passed back to the
	// upper layer if an error occurs on the send of a message and is
	// retrieved with each undelivered message
	Context uint32

	// Association Id is ignored in one-to-one mode
	AssocId int32
}

SndInfo structure specifies SCTP options for sending SCTP messages Used in SCTPConn.WriteMsg functions

type Status

type Status struct {
	// Association Id is ignored in one-to-one mode
	AssocId int32

	// Contains the association's current state, i.e.,
	// one of the values defined in Status state values.
	State int32

	// Contains the association peer's current receiver window size.
	Rwnd uint32

	// Number of unacknowledged DATA chunks.
	UnackData uint16

	// Number of DATA chunks pending receipt.
	PendingData uint16

	// Number of streams that the peer will be using outbound.
	InStreams uint16

	// Number of outbound streams that the endpoint is allowed to use.
	OutStreams uint16

	// The size at which SCTP fragmentation will occur.
	FragmentationPoint uint32

	// Information on the current primary peer address.
	PrimaryAddrInfo *PeerAddrInfo
}

Status structure holds current status information about an association, including association state, peer receiver window size, number of unacknowledged DATA chunks, and number of DATA chunks pending receipt.

Directories

Path Synopsis
perf-test

Jump to

Keyboard shortcuts

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