transport

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2021 License: BSD-2-Clause Imports: 15 Imported by: 1

Documentation

Overview

Package transport provides implementation of QUIC transport protocol.

To create a server or client connection:

serverConfig := transport.NewConfig() // Server also requires a TLS certificate
server, err := transport.Accept(scid, odcid, serverConfig)

clientConfig := transport.NewConfig()
client, err := transport.Connect(scid, dcid, clientConfig)

To use the connection, feed it with input data and then get output data sending to peer:

for { // Loop until the connection is closed
	timeout := server.Timeout()
	// (A negative timeout means that the timer should be disarmed)
	select {
		case data := <-dataChanel:  // Got data from peer
			n, err := conn.Write(data)
		case <-time.After(timeout): // Got receiving timeout
			n, err := conn.Write(nil)
	}
	// Get and process connection events
	events = conn.Events(events)
	for { // Loop until err != nil or n == 0
		n, err := conn.Read(buf)
		// Send buf[:n] to peer
	}
}

Index

Constants

View Source
const (
	// MaxCIDLength is the maximum length of a Connection ID
	MaxCIDLength = 20
	// MinInitialPacketSize is the QUIC minimum packet size when it contains Initial packet.
	// https://www.rfc-editor.org/rfc/rfc9000.html#section-14
	MinInitialPacketSize = 1200
)
View Source
const (
	NoError                 uint64 = 0x0
	InternalError           uint64 = 0x1
	ConnectionRefused       uint64 = 0x2
	FlowControlError        uint64 = 0x3
	StreamLimitError        uint64 = 0x4
	StreamStateError        uint64 = 0x5
	FinalSizeError          uint64 = 0x6
	FrameEncodingError      uint64 = 0x7
	TransportParameterError uint64 = 0x8
	ConnectionIDLimitError  uint64 = 0x9
	ProtocolViolation       uint64 = 0xa
	InvalidToken            uint64 = 0xb
	ApplicationError        uint64 = 0xc
	CryptoBufferExceeded    uint64 = 0xd
	KeyUpdateError          uint64 = 0xe
	AEADLimitReached        uint64 = 0xf
	CryptoError             uint64 = 0x100
)

https://www.rfc-editor.org/rfc/rfc9000.html#section-20

View Source
const (
	EventConnOpen   = "conn_open"   // New connection established.
	EventConnClosed = "conn_closed" // Connection closed.

	EventStreamOpen      = "stream_open"      // A new stream has been opened by peer.
	EventStreamReadable  = "stream_readable"  // Received stream data and readable or reset by peer.
	EventStreamWritable  = "stream_writable"  // Stream is unblocked and can add more data or stopped by peer.
	EventStreamCreatable = "stream_creatable" // Maximum streams increased by peer.
	EventStreamComplete  = "stream_complete"  // All sending data has been acked.
	EventStreamClosed    = "stream_closed"    // Stream is fully closed and no longer available.

	EventDatagramOpen     = "datagram_open"     // Datagram is supported by peer.
	EventDatagramWritable = "datagram_writable" // Datagram buffer is writable.
	EventDatagramReadable = "datagram_readable" // Received datagram.
)

Suppported event types

Variables

This section is empty.

Functions

func IsPacketDropped added in v0.0.5

func IsPacketDropped(err error) string

IsPacketDropped returns a reason (non empty string) if err is a packet dropped, so the packet can either be discarded or bufferred for later use. This function should only be used for error returned by Conn.Write. See triggers at https://quicwg.org/qlog/draft-ietf-quic-qlog-quic-events.html#section-3.3.7

func IsVersionSupported added in v0.0.6

func IsVersionSupported(version uint32) bool

IsVersionSupported returns true when the provided QUIC transport version is supported.

func NegotiateVersion

func NegotiateVersion(b, dcid, scid []byte) (int, error)

NegotiateVersion writes version negotiation packet to b.

func Retry

func Retry(b, dcid, scid, odcid, token []byte) (int, error)

Retry writes retry packet to b.

Types

type Config

type Config struct {
	TLS     *tls.Config // TLS configuration, required for server.
	Params  Parameters  // QUIC transport parameters.
	Version uint32      // QUIC version.

	MaxPacketsPerKey uint64 // Override default maximum number of encrypted packets for each AEAD key.
}

Config is a QUIC connection configuration. This implementaton utilizes tls.Config.Rand and tls.Config.Time if available.

func NewConfig

func NewConfig() *Config

NewConfig creates a default configuration.

type Conn

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

Conn is a QUIC connection.

func Accept

func Accept(scid, odcid []byte, config *Config) (*Conn, error)

Accept creates a server connection. scid is the source connection id. odcid is the optional original destination connection id.

func Connect

func Connect(scid, dcid []byte, config *Config) (*Conn, error)

Connect creates a client connection. scid is the source connection id. dcid is the destination connection id.

func (*Conn) Close

func (s *Conn) Close(errCode uint64, reason string, app bool) error

Close sets the connection to Closing state if it is not in Draining or Closed state. Packet generated from calling Read afterward will include a ConnectionClose frame. If the peer already initiated connection closing with an error, this function will immediately set connection state to Closed and return that error. https://www.rfc-editor.org/rfc/rfc9000.html#section-10.2.2

func (*Conn) ConnectionState added in v0.0.4

func (s *Conn) ConnectionState() ConnectionState

ConnectionState returns the current connection state and statistics.

func (*Conn) Datagram added in v0.0.4

func (s *Conn) Datagram() *Datagram

Datagram returns a Datagram associated to this QUIC connection.

func (*Conn) Delay added in v0.0.7

func (s *Conn) Delay() time.Duration

Delay returns duration that application should wait to delivery the last packet it got from Read. A non-positive duration means the packet should be delivered immediately.

func (*Conn) Events

func (s *Conn) Events(events []Event) []Event

Events consumes received connection events as well as stream and datagram events. It appends to provided events slice and clears received events.

func (*Conn) HandshakeComplete added in v0.0.7

func (s *Conn) HandshakeComplete() bool

HandshakeComplete returns true when connection handshake is completed and not closing.

func (*Conn) IsClosed

func (s *Conn) IsClosed() bool

IsClosed returns true when the connection state is closed.

func (*Conn) Read

func (s *Conn) Read(b []byte) (int, error)

Read produces data for sending to the client.

func (*Conn) SetLogger added in v0.0.4

func (s *Conn) SetLogger(fn func(LogEvent))

SetLogger sets handler for received events.

func (*Conn) Stream

func (s *Conn) Stream(id uint64) (*Stream, error)

Stream returns an openned stream or create a local stream if it does not exist. Client-initiated streams have even-numbered stream IDs and server-initiated streams have odd-numbered stream IDs.

func (*Conn) Timeout

func (s *Conn) Timeout() time.Duration

Timeout returns the amount of time until the next timeout event. A negative timeout means that the timer should be disarmed.

func (*Conn) Write

func (s *Conn) Write(b []byte) (int, error)

Write consumes received data. NOTE: b will be modified as data is decrypted directly to b.

type ConnectionState added in v0.0.4

type ConnectionState struct {
	State string // Internal state

	// Received packets
	RecvPackets uint64
	RecvBytes   uint64
	// Sent packets
	SentPackets uint64
	SentBytes   uint64
	// Lost packets
	LostPackets uint64
	LostBytes   uint64
	// Peer transport parameters.
	PeerParams Parameters
	// TLS handshake state.
	TLS tls.ConnectionState
	// Local and peer error when closing connection.
	LocalError error
	PeerError  error
}

ConnectionState is the state and statistics about the connection.

type Datagram added in v0.0.4

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

Datagram provides unreliable datagrams over QUIC transport. https://quicwg.org/datagram/draft-ietf-quic-datagram.html

func (*Datagram) Read added in v0.0.4

func (s *Datagram) Read(b []byte) (int, error)

Read reads received datagrams. If the size of provided buffer is less than the datagram size, io.ErrShortBuffer will be returned. See MaxDatagramPayloadSize in Parameters for maximum datagram size this connect can receive.

func (*Datagram) Write added in v0.0.4

func (s *Datagram) Write(b []byte) (int, error)

Write makes a copy of the data and push to this datagram buffer for sending. The length of b must not exceed the maximum datagram size that peer can receive. This value is specified in the connection event EventDatagramWritable.

type Error

type Error struct {
	Code   uint64
	Reason string
	// App indicates whether this error is an application error.
	// Application error is returned when reading from or writing to a terminated stream.
	// https://www.rfc-editor.org/rfc/rfc9000#section-20.2
	App bool
}

Error is the QUIC transport error. https://www.rfc-editor.org/rfc/rfc9000#section-20.1

func (*Error) Error

func (e *Error) Error() string

type Event added in v0.0.4

type Event struct {
	Type string // Type of event
	Data uint64 // Data associated with the event. For stream events, this is Stream ID.
}

Event is a union structure of all events.

func (Event) String added in v0.0.4

func (s Event) String() string
type Header struct {
	Type    string
	DCID    []byte
	SCID    []byte // Not applicable in 1RTT packet
	Token   []byte // Only in Initial and Retry packet
	Version uint32 // Not applicable in 1RTT packet
}

Header is for decoding public information of a QUIC packet. This data allows to process packet prior to decryption.

func (*Header) Decode added in v0.0.2

func (s *Header) Decode(b []byte, dcil int) (int, error)

Decode decodes public information from a QUIC packet. dcil is the length of connection id in short header packets. Note: all resulted slices (CIDs) are references to data in b so they will be invalid when b is modified.

func (*Header) String

func (s *Header) String() string

type LogEvent added in v0.0.4

type LogEvent struct {
	Time time.Time
	Name string
	Data []byte
}

LogEvent is event sent by connection. Application must not retain Data as it is from internal buffers.

func (LogEvent) String added in v0.0.4

func (s LogEvent) String() string

type Parameters

type Parameters struct {
	// OriginalDestinationCID is the DCID from the first Initial packet.
	// This parameter is only sent by server.
	OriginalDestinationCID []byte
	// InitialSourceCID is the SCID of the first Initial packet.
	InitialSourceCID []byte
	// RetrySourceCID is the SCID of Retry packet.
	// This parameter is only sent by server.
	RetrySourceCID []byte
	// StatelessResetToken is used in verifying a stateless reset and must be 16 bytes.
	// This parameter is only sent by server.
	StatelessResetToken []byte

	// MaxIdleTimeout is the duration that if the connection remains idle, it will be closed.
	MaxIdleTimeout time.Duration
	// MaxUDPPayloadSize is the maximum size of UDP payloads that the endpoint is willing to receive.
	MaxUDPPayloadSize uint64

	InitialMaxData                 uint64
	InitialMaxStreamDataBidiLocal  uint64
	InitialMaxStreamDataBidiRemote uint64
	InitialMaxStreamDataUni        uint64
	InitialMaxStreamsBidi          uint64
	InitialMaxStreamsUni           uint64

	// AckDelayExponent is the exponent used to decode ACK Delay field.
	// A default value of 3 will be used if this value is zero. Values above 20 are invalid.
	AckDelayExponent uint64
	// MaxAckDelay is the maximum time the endpoint will delay sending acknowledgement.
	MaxAckDelay time.Duration

	// ActiveConnectionIDLimit is the maximum number of connection IDs from the peer that
	// an endpoint is willing to store.
	ActiveConnectionIDLimit uint64
	// MaxDatagramFramePayloadSize is the maximum size of payload in a DATAGRAM frame the endpoint
	// is willing to receive. DATAGRAM is disabled when the value is zero.
	// See https://quicwg.org/datagram/draft-ietf-quic-datagram.html#section-3
	MaxDatagramFramePayloadSize uint64
	// DisableActiveMigration indicates the endpoint does not support active connection migration.
	DisableActiveMigration bool
}

Parameters is QUIC transport parameters. https://www.rfc-editor.org/rfc/rfc9000#section-7.4

func (*Parameters) String added in v0.0.7

func (s *Parameters) String() string

type Stream

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

Stream is a data stream. https://www.rfc-editor.org/rfc/rfc9000#section-2

func (*Stream) Close

func (s *Stream) Close() error

Close ends the sending part of the stream (clean termination) if it is a bidirectional stream or locally created. Closing a receive-only stream is no-op.

func (*Stream) CloseRead added in v0.0.4

func (s *Stream) CloseRead(errorCode uint64) error

CloseRead aborts the reading part of the stream and requests closure. Closing a send-only stream will result in error stream_state_error.

func (*Stream) CloseWrite added in v0.0.4

func (s *Stream) CloseWrite(errorCode uint64) error

CloseWrite abruptly terminates the sending part of a stream. Closing a receive-only stream will result in error stream_state_error.

func (*Stream) Read

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

Read reads data from recv stream. Reading from a send-only or closed stream will result in error io.EOF.

func (*Stream) String

func (s *Stream) String() string

String returns state of the stream.

func (*Stream) Write

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

Write writes data to send stream. Writing to a read-only or closed stream will result in error io.EOF.

func (*Stream) WriteString added in v0.0.4

func (s *Stream) WriteString(b string) (int, error)

WriteString writes the contents of string b to the stream.

func (*Stream) WriteTo added in v0.0.8

func (s *Stream) WriteTo(w io.Writer) (int64, error)

WriteTo writes stream data to w until there is no more data or when an error occurs.

Jump to

Keyboard shortcuts

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