net

package
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: May 10, 2020 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package net manages the accepting network connections/messages and routing the data upward for the protocols to consume.

Index

Constants

View Source
const (
	// ReadBufferSize const is the default value used to set the socket option SO_RCVBUF
	ReadBufferSize = 5 * 1024 * 1024
	// WriteBufferSize const is the default value used to set the socket option SO_SNDBUF
	WriteBufferSize = 5 * 1024 * 1024
	// TCPKeepAlive sets whether KeepAlive is active or not on the socket
	TCPKeepAlive = true
	// TCPKeepAlivePeriod sets the interval of KeepAlive
	TCPKeepAlivePeriod = 10 * time.Second
)
View Source
const DefaultMessageQueueSize uint = 5120

DefaultMessageQueueSize is the buffer size of each queue mentioned above. (queues are buffered channels)

View Source
const DefaultQueueCount uint = 6

DefaultQueueCount is the default number of messages queue we hold. messages queues are used to serialize message receiving

View Source
const MessageQueueSize = 250

MessageQueueSize is the size for queue of messages before pushing them on the socket

Variables

View Source
var (
	// ErrClosedIncomingChannel is sent when the connection is closed because the underlying formatter incoming channel was closed
	ErrClosedIncomingChannel = errors.New("unexpected closed incoming channel")
	// ErrConnectionClosed is sent when the connection is closed after Close was called
	ErrConnectionClosed = errors.New("connections was intentionally closed")
)
View Source
var (
	// ErrTriedToSetupExistingConn occurs when handshake packet is sent twice on a connection
	ErrTriedToSetupExistingConn = errors.New("tried to setup existing connection")
	// ErrMsgExceededLimit occurs when a received message size exceeds the defined message size
	ErrMsgExceededLimit = errors.New("message size exceeded limit")
)
View Source
var ErrAlreadyClosed = errors.New("connection is already closed")

ErrAlreadyClosed is an error for when `Close` is called on a closed connection.

View Source
var IPv4LoopbackAddress = net.IP{127, 0, 0, 1}

IPv4LoopbackAddress is a local IPv4 loopback

Functions

func NodeAddr

func NodeAddr(info *node.Info) *net.UDPAddr

NodeAddr makes a UDPAddr from a Info struct

func Temporary

func Temporary(err error) bool

Temporary checks whether the given error should be considered temporary.

Types

type Connection

type Connection interface {
	fmt.Stringer

	ID() string
	RemotePublicKey() p2pcrypto.PublicKey
	SetRemotePublicKey(key p2pcrypto.PublicKey)
	Created() time.Time

	RemoteAddr() net.Addr

	Session() NetworkSession
	SetSession(session NetworkSession)

	Send(m []byte) error
	Close() error
	Closed() bool
}

Connection is an interface stating the API of all secured connections in the system

type ConnectionMock

type ConnectionMock struct {
	Addr net.Addr
	// contains filtered or unexported fields
}

ConnectionMock mocks connections.

func NewConnectionMock

func NewConnectionMock(key p2pcrypto.PublicKey) *ConnectionMock

NewConnectionMock creates a ConnectionMock.

func (*ConnectionMock) Close

func (cm *ConnectionMock) Close() error

Close mocks the interface.

func (ConnectionMock) Closed

func (cm ConnectionMock) Closed() bool

Closed mocks the interface.

func (ConnectionMock) Created added in v0.1.2

func (cm ConnectionMock) Created() time.Time

Created mocks the connection interface.

func (ConnectionMock) ID

func (cm ConnectionMock) ID() string

ID mocks the connection interface.

func (ConnectionMock) IncomingChannel

func (cm ConnectionMock) IncomingChannel() chan []byte

IncomingChannel mocks the interface.

func (*ConnectionMock) RemoteAddr

func (cm *ConnectionMock) RemoteAddr() net.Addr

RemoteAddr mocks the interface.

func (ConnectionMock) RemotePublicKey

func (cm ConnectionMock) RemotePublicKey() p2pcrypto.PublicKey

RemotePublicKey mocks the interface.

func (*ConnectionMock) Send

func (cm *ConnectionMock) Send(m []byte) error

Send mocks the interface.

func (ConnectionMock) SendCount

func (cm ConnectionMock) SendCount() int32

SendCount mutates the mock.

func (ConnectionMock) Session

func (cm ConnectionMock) Session() NetworkSession

Session mocks the interface.

func (ConnectionMock) SetCreated added in v0.1.2

func (cm ConnectionMock) SetCreated(time2 time.Time)

SetCreated mutate the mock.

func (*ConnectionMock) SetRemotePublicKey

func (cm *ConnectionMock) SetRemotePublicKey(key p2pcrypto.PublicKey)

SetRemotePublicKey mutates the mock.

func (*ConnectionMock) SetSendDelay

func (cm *ConnectionMock) SetSendDelay(delayMs int)

SetSendDelay mutates the mock.

func (*ConnectionMock) SetSendResult

func (cm *ConnectionMock) SetSendResult(err error)

SetSendResult mutates the mock.

func (*ConnectionMock) SetSession

func (cm *ConnectionMock) SetSession(session NetworkSession)

SetSession mutates the mock.

func (ConnectionMock) String

func (cm ConnectionMock) String() string

String mocks the interface

type ConnectionSource

type ConnectionSource int

ConnectionSource specifies the connection originator - local or remote node.

const (
	Local ConnectionSource = iota
	Remote
)

ConnectionSource values

type ConnectionWithErr

type ConnectionWithErr struct {
	Conn Connection
	Err  error
}

ConnectionWithErr is a pair of Connection and an error occurred within the connection

type FormattedConnection

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

FormattedConnection is an io.Writer and an io.Closer A network connection supporting full-duplex messaging

func (*FormattedConnection) Close

func (c *FormattedConnection) Close() error

Close closes the connection (implements io.Closer). It is go safe.

func (*FormattedConnection) Closed

func (c *FormattedConnection) Closed() bool

Closed returns whether the connection is closed

func (*FormattedConnection) Created added in v0.1.2

func (c *FormattedConnection) Created() time.Time

Created is the time the connection was created

func (*FormattedConnection) ID

func (c *FormattedConnection) ID() string

ID returns the channel's ID

func (*FormattedConnection) RemoteAddr

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

RemoteAddr returns the channel's remote peer address

func (*FormattedConnection) RemotePublicKey

func (c *FormattedConnection) RemotePublicKey() p2pcrypto.PublicKey

RemotePublicKey returns the remote peer's public key

func (*FormattedConnection) Send

func (c *FormattedConnection) Send(m []byte) error

Send pushes a message into the queue if the connection is not closed.

func (*FormattedConnection) SendSock

func (c *FormattedConnection) SendSock(m []byte) error

SendSock sends a message directly on the socket without waiting for the queue.

func (*FormattedConnection) Session

func (c *FormattedConnection) Session() NetworkSession

Session returns the network session

func (*FormattedConnection) SetRemotePublicKey

func (c *FormattedConnection) SetRemotePublicKey(key p2pcrypto.PublicKey)

SetRemotePublicKey sets the remote peer's public key

func (*FormattedConnection) SetSession

func (c *FormattedConnection) SetSession(session NetworkSession)

SetSession sets the network session

func (*FormattedConnection) String

func (c *FormattedConnection) String() string

String returns a string describing the connection

type HandshakeData

type HandshakeData struct {
	ClientVersion string
	NetworkID     int32
	Port          uint16
}

HandshakeData is the handshake message struct

type IncomingMessageEvent

type IncomingMessageEvent struct {
	Conn    Connection
	Message []byte
}

IncomingMessageEvent is the event reported on new incoming message, it contains the message and the Connection carrying the message

type ManagedConnection

type ManagedConnection interface {
	Connection
	// contains filtered or unexported methods
}

ManagedConnection in an interface extending Connection with some internal methods that are required for Net to manage Connections

type MsgConnection added in v0.1.2

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

MsgConnection is an io.Writer and an io.Closer A network connection supporting full-duplex messaging It resembles the Connection interface but suits a packet oriented socket.

func (*MsgConnection) Close added in v0.1.2

func (c *MsgConnection) Close() error

Close closes the connection (implements io.Closer). It is go safe.

func (*MsgConnection) Closed added in v0.1.2

func (c *MsgConnection) Closed() bool

Closed returns whether the connection is closed

func (*MsgConnection) Created added in v0.1.2

func (c *MsgConnection) Created() time.Time

Created saves the time when the connection was created

func (*MsgConnection) ID added in v0.1.2

func (c *MsgConnection) ID() string

ID returns the channel's ID

func (*MsgConnection) RemoteAddr added in v0.1.2

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

RemoteAddr returns the channel's remote peer address

func (*MsgConnection) RemotePublicKey added in v0.1.2

func (c *MsgConnection) RemotePublicKey() p2pcrypto.PublicKey

RemotePublicKey returns the remote peer's public key

func (*MsgConnection) Send added in v0.1.2

func (c *MsgConnection) Send(m []byte) error

Send pushes a message to the messages queue

func (*MsgConnection) SendSock added in v0.1.2

func (c *MsgConnection) SendSock(m []byte) error

SendSock sends a message directly on the socket

func (*MsgConnection) Session added in v0.1.2

func (c *MsgConnection) Session() NetworkSession

Session returns the network session

func (*MsgConnection) SetRemotePublicKey added in v0.1.2

func (c *MsgConnection) SetRemotePublicKey(key p2pcrypto.PublicKey)

SetRemotePublicKey sets the remote peer's public key

func (*MsgConnection) SetSession added in v0.1.2

func (c *MsgConnection) SetSession(session NetworkSession)

SetSession sets the network session

func (*MsgConnection) String added in v0.1.2

func (c *MsgConnection) String() string

String returns a string describing the connection

type Net

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

Net is a connection factory able to dial remote endpoints Net clients should register all callbacks Connections may be initiated by Dial() or by remote clients connecting to the listen address It provides full duplex messaging functionality over the same tcp/ip connection Net has no channel events processing loops - clients are responsible for polling these channels and popping events from them

func NewNet

func NewNet(conf config.Config, localEntity node.LocalNode, logger log.Log) (*Net, error)

NewNet creates a new network. It attempts to tcp listen on address. e.g. localhost:1234 .

func (*Net) Dial

func (n *Net) Dial(ctx context.Context, address net.Addr, remotePubkey p2pcrypto.PublicKey) (Connection, error)

Dial a remote server with provided time out address:: net.Addr Returns established connection that local clients can send messages to or error if failed to establish a connection, currently only secured connections are supported

func (*Net) EnqueueMessage

func (n *Net) EnqueueMessage(event IncomingMessageEvent)

EnqueueMessage inserts a message into a queue, to decide on which queue to send the message to it sum the remote public key bytes as integer to segment to queueCount queues.

func (*Net) HandlePreSessionIncomingMessage

func (n *Net) HandlePreSessionIncomingMessage(c Connection, message []byte) error

HandlePreSessionIncomingMessage establishes session with the remote peer and update the Connection with the new session

func (*Net) IncomingMessages

func (n *Net) IncomingMessages() []chan IncomingMessageEvent

IncomingMessages returns a slice of channels which incoming messages are delivered on the receiver should iterate on all the channels and read all messages. to sync messages order but enable parallel messages handling.

func (*Net) LocalAddr

func (n *Net) LocalAddr() net.Addr

LocalAddr returns the local listening address. panics before calling Start or if Start errored

func (*Net) LocalNode

func (n *Net) LocalNode() node.LocalNode

LocalNode return's the local node descriptor

func (*Net) Logger

func (n *Net) Logger() log.Log

Logger returns a reference to logger

func (*Net) NetworkID

func (n *Net) NetworkID() int8

NetworkID retuers Net's network ID

func (*Net) Shutdown

func (n *Net) Shutdown()

Shutdown initiate a graceful closing of the TCP listener and all other internal routines

func (*Net) Start

func (n *Net) Start(listener net.Listener)

Start begins accepting connections from the listener socket

func (*Net) SubscribeClosingConnections

func (n *Net) SubscribeClosingConnections(f func(connection ConnectionWithErr))

SubscribeClosingConnections registers a callback for a new connection event. all registered callbacks are called before moving.

func (*Net) SubscribeOnNewRemoteConnections

func (n *Net) SubscribeOnNewRemoteConnections(f func(event NewConnectionEvent))

SubscribeOnNewRemoteConnections registers a callback for a new connection event. all registered callbacks are called before moving.

type NetworkMock

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

NetworkMock is a mock struct

func NewNetworkMock

func NewNetworkMock() *NetworkMock

NewNetworkMock is a mock

func (*NetworkMock) Dial

func (n *NetworkMock) Dial(ctx context.Context, address net.Addr, remotePublicKey p2pcrypto.PublicKey) (Connection, error)

Dial dials

func (*NetworkMock) DialCount

func (n *NetworkMock) DialCount() int32

DialCount gets the dial count

func (*NetworkMock) EnqueueMessage

func (n *NetworkMock) EnqueueMessage(event IncomingMessageEvent)

EnqueueMessage return channel of IncomingMessages

func (*NetworkMock) HandlePreSessionIncomingMessage

func (n *NetworkMock) HandlePreSessionIncomingMessage(c Connection, msg []byte) error

HandlePreSessionIncomingMessage and stuff

func (*NetworkMock) IncomingMessages

func (n *NetworkMock) IncomingMessages() []chan IncomingMessageEvent

IncomingMessages return channel of IncomingMessages

func (*NetworkMock) Logger

func (n *NetworkMock) Logger() log.Log

Logger return the logger

func (*NetworkMock) NetworkID

func (n *NetworkMock) NetworkID() int8

NetworkID is netid

func (NetworkMock) PreSessionCount

func (n NetworkMock) PreSessionCount() int32

PreSessionCount counts

func (NetworkMock) PublishClosingConnection

func (n NetworkMock) PublishClosingConnection(con ConnectionWithErr)

PublishClosingConnection is a hack to expose the above method in the mock but still impl the same interface

func (NetworkMock) PublishNewRemoteConnection

func (n NetworkMock) PublishNewRemoteConnection(nce NewConnectionEvent)

PublishNewRemoteConnection and stuff

func (*NetworkMock) SetDialDelayMs

func (n *NetworkMock) SetDialDelayMs(delay int8)

SetDialDelayMs sets delay

func (*NetworkMock) SetDialResult

func (n *NetworkMock) SetDialResult(err error)

SetDialResult is a mock

func (*NetworkMock) SetNextDialSessionID

func (n *NetworkMock) SetNextDialSessionID(sID []byte)

SetNextDialSessionID mutates the mock to change the next returned session id

func (*NetworkMock) SetPreSessionResult

func (n *NetworkMock) SetPreSessionResult(err error)

SetPreSessionResult does this

func (*NetworkMock) SubscribeClosingConnections

func (n *NetworkMock) SubscribeClosingConnections(f func(connection ConnectionWithErr))

SubscribeClosingConnections subscribes on new connections

func (*NetworkMock) SubscribeOnNewRemoteConnections

func (n *NetworkMock) SubscribeOnNewRemoteConnections(f func(event NewConnectionEvent))

SubscribeOnNewRemoteConnections subscribes on new connections

type NetworkSession

type NetworkSession interface {
	ID() p2pcrypto.PublicKey // Unique session id, currently the peer pubkey TODO: @noam use pubkey from conn and remove this

	OpenMessage(boxedMessage []byte) ([]byte, error) // decrypt data using session dec key
	SealMessage(message []byte) []byte               // encrypt data using session enc key
}

NetworkSession is an authenticated network session between 2 peers. Sessions may be used between 'connections' until they expire. Session provides the encryptor/decryptor for all messages exchanged between 2 peers. enc/dec is using an ephemeral sym key exchanged securely between the peers via the handshake protocol The handshake protocol goal is to create an authenticated network session.

func NewNetworkSession

func NewNetworkSession(sharedSecret p2pcrypto.SharedSecret, peerPubkey p2pcrypto.PublicKey) NetworkSession

NewNetworkSession creates a new network session based on provided data

type NewConnectionEvent

type NewConnectionEvent struct {
	Conn Connection
	Node *node.Info
}

NewConnectionEvent is a struct holding a new created connection and a node info.

type ReadWriteCloserMock

type ReadWriteCloserMock struct {
}

ReadWriteCloserMock is a mock of ReadWriteCloserMock

func (ReadWriteCloserMock) Close

func (m ReadWriteCloserMock) Close() error

Close mocks close

func (ReadWriteCloserMock) Read

func (m ReadWriteCloserMock) Read(p []byte) (n int, err error)

Read reads something

func (ReadWriteCloserMock) RemoteAddr

func (m ReadWriteCloserMock) RemoteAddr() net.Addr

RemoteAddr mocks remote addr return

func (ReadWriteCloserMock) Write

func (m ReadWriteCloserMock) Write(p []byte) (n int, err error)

Write mocks write

type SessionMock

type SessionMock struct {
	SealMessageFunc func(message []byte) []byte
	OpenMessageFunc func(boxedMessage []byte) ([]byte, error)
	// contains filtered or unexported fields
}

SessionMock mocks NetworkSession.

func NewSessionMock

func NewSessionMock(pubkey p2pcrypto.PublicKey) *SessionMock

NewSessionMock creates a new mock for given public key.

func (SessionMock) ID

ID is a mock.

func (SessionMock) OpenMessage

func (sm SessionMock) OpenMessage(boxedMessage []byte) ([]byte, error)

OpenMessage is a mock.

func (SessionMock) SealMessage

func (sm SessionMock) SealMessage(message []byte) []byte

SealMessage is a mock.

type UDPListener added in v0.1.6

type UDPListener interface {
	LocalAddr() net.Addr
	Close() error
	WriteToUDP(final []byte, addr *net.UDPAddr) (int, error)
	ReadFrom(p []byte) (n int, addr net.Addr, err error)
	WriteTo(p []byte, addr net.Addr) (n int, err error)
	SetDeadline(t time.Time) error
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
}

UDPListener is the api required for listening on udp messages.

type UDPMessageEvent

type UDPMessageEvent struct {
	From     p2pcrypto.PublicKey
	FromAddr net.Addr
	Message  []byte
}

UDPMessageEvent is an event about a udp message. passed through a channel

type UDPNet

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

UDPNet is used to listen on or send udp messages

func NewUDPNet

func NewUDPNet(config config.Config, localEntity node.LocalNode, log log.Log) (*UDPNet, error)

NewUDPNet creates a UDPNet

func (*UDPNet) Dial added in v0.1.2

func (n *UDPNet) Dial(ctx context.Context, address net.Addr, remotePublicKey p2pcrypto.PublicKey) (Connection, error)

Dial creates a Connection interface which is wrapped around a udp socket with a session and start listening on messages form it. it uses the `connect` syscall

func (*UDPNet) EnqueueMessage added in v0.1.2

func (n *UDPNet) EnqueueMessage(ime IncomingMessageEvent)

EnqueueMessage pushes an incoming message event into the queue

func (*UDPNet) HandlePreSessionIncomingMessage added in v0.1.2

func (n *UDPNet) HandlePreSessionIncomingMessage(c Connection, msg []byte) error

HandlePreSessionIncomingMessage is used to satisfy an api similar to the tcpnet. not used here.

func (*UDPNet) IncomingMessages

func (n *UDPNet) IncomingMessages() chan IncomingMessageEvent

IncomingMessages is a channel where incoming UDPMessagesEvents will stream

func (*UDPNet) LocalAddr

func (n *UDPNet) LocalAddr() net.Addr

LocalAddr returns the local listening addr, will panic before running Start. or if start errored

func (*UDPNet) NetworkID added in v0.1.2

func (n *UDPNet) NetworkID() int8

NetworkID returns the network id given and used for creating a session.

func (*UDPNet) Send

func (n *UDPNet) Send(to *node.Info, data []byte) error

Send writes a udp packet to the target with the given data

func (*UDPNet) Shutdown

func (n *UDPNet) Shutdown()

Shutdown stops listening and closes the connection.

func (*UDPNet) Start

func (n *UDPNet) Start(listener UDPListener)

Start will start reading messages from the udp socket and pass them up the channels

func (*UDPNet) SubscribeClosingConnections added in v0.1.2

func (n *UDPNet) SubscribeClosingConnections(f func(connection ConnectionWithErr))

SubscribeClosingConnections registers a callback for a new connection event. all registered callbacks are called before moving.

func (*UDPNet) SubscribeOnNewRemoteConnections added in v0.1.2

func (n *UDPNet) SubscribeOnNewRemoteConnections(f func(event NewConnectionEvent))

SubscribeOnNewRemoteConnections registers a callback for a new connection event. all registered callbacks are called before moving.

Directories

Path Synopsis
delimited
Package delimited implements a reader and writer for simple streams of length-delimited byte records.
Package delimited implements a reader and writer for simple streams of length-delimited byte records.

Jump to

Keyboard shortcuts

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