network

package
v0.0.0-...-9fbb145 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2021 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// PlainKCP is an unencrypted KCP connection.
	PlainKCP ConnType = "kcp"
	// TLS is a TLS encrypted connection over KCP.
	TLS = "tls"
	// Local is a channel based connection type.
	Local = "local"
	// InvalidConnType is an invalid connection type.
	InvalidConnType = "wrong"
)
View Source
const MaxRetryConnect = 3

MaxRetryConnect defines how many times we should try to connect.

View Source
const NamespaceBodyType = NamespaceURL + "/protocolType/"

NamespaceBodyType is the namespace used for PacketTypeID

View Source
const NamespaceURL = "https://cypherium.io/"

NamespaceURL is the basic namespace used for uuid XXX should move that to external of the library as not every cothority/packages should be expected to use that.

View Source
const WaitRetry = 20 * time.Millisecond

WaitRetry is the timeout on connection-setups.

Variables

View Source
var ErrCanceled = errors.New("Operation Canceled")

ErrCanceled means something went wrong in the sending or receiving part.

View Source
var ErrClosed = errors.New("Connection Closed")

ErrClosed is when a connection has been closed.

View Source
var ErrEOF = errors.New("EOF")

ErrEOF is when the connection sends an EOF signal (mostly because it has been shut down).

View Source
var ErrTimeout = errors.New("Timeout Error")

ErrTimeout is raised if the timeout has been reached.

View Source
var ErrUnknown = errors.New("Unknown Error")

ErrUnknown is an unknown error.

View Source
var ErrorType = MessageTypeID(uuid.Nil)

ErrorType is reserved by the network library. When you receive a message of ErrorType, it is generally because an error happened, then you can call Error() on it.

View Source
var ReadTimeout = 3 * time.Minute // 60 * time.Second

a connection will return an io.EOF after ReadTimeout if nothing has been sent.

View Source
var ServerIdentityType = RegisterMessage(ServerIdentity{})

ServerIdentityType can be used to recognise an ServerIdentity-message

Functions

func DefaultConstructors

func DefaultConstructors() protobuf.Constructors

DefaultConstructors gives a default constructor for protobuf

func DumpTypes

func DumpTypes()

DumpTypes is used for debugging - it prints out all known types

func GlobalBind

func GlobalBind(address string) (string, error)

GlobalBind returns the global-binding address. Given any IP:PORT combination, it will return ":PORT".

func Marshal

func Marshal(msg Message) ([]byte, error)

Marshal outputs the type and the byte representation of a structure. It first marshals the type as a uuid, i.e. a 16 byte length slice, then the struct encoded by protobuf. That slice of bytes can be then decoded with Unmarshal. msg must be a pointer to the message.

func Unmarshal

func Unmarshal(buf []byte) (MessageTypeID, Message, error)

Unmarshal returns the type and the message out of a buffer. One can cast the resulting Message to a *pointer* of the underlying type, i.e. it returns a pointer. The type must be registered to the network library in order to be decodable and the buffer must have been generated by Marshal otherwise it returns an error.

Types

type Address

type Address string

Address contains the ConnType and the actual network address. It is used to connect to a remote host with a Conn and to listen by a Listener. A network address holds an IP address and the port number joined by a colon. It doesn't support IPv6 yet.

func NewAddress

func NewAddress(t ConnType, network string) Address

NewAddress takes a connection type and the raw address. It returns a correctly formatted address, which will be of type t. It doesn't do any checking of ConnType or network.

func NewKCPAddress

func NewKCPAddress(addr string) Address

NewKCPAddress returns a new Address that has type PlainKCP with the given address addr.

func (Address) ConnType

func (a Address) ConnType() ConnType

ConnType returns the connection type from the address. It returns InvalidConnType if the address is not valid or if the connection type is not known.

func (Address) Host

func (a Address) Host() string

Host returns the host part of the address. ex: "kcp://127.0.0.1:2000" => "127.0.0.1" In case of an error, it returns an empty string.

func (Address) IsHostname

func (a Address) IsHostname() bool

IsHostname returns true if the address is defined by a VALID DNS name

func (Address) NetworkAddress

func (a Address) NetworkAddress() string

NetworkAddress returns the network address part of the address, which is the host and the port joined by a colon. It returns an empty string the address is not valid

func (Address) NetworkAddressResolved

func (a Address) NetworkAddressResolved() string

NetworkAddressResolved returns the network address of the address, but resolved. That is: the hostname resolved and the port joined by a colon. It returns an empty string if the address is not valid.

func (Address) Port

func (a Address) Port() string

Port will return the port part of the Address. In the case of an invalid address or an invalid port, it will return "".

func (Address) Resolve

func (a Address) Resolve() string

Resolve returns the IP address associated to the hostname that represents the address a. If a is defined by an IP address (*.*.*.*) or if the hostname is not valid, the empty string is returned

func (Address) String

func (a Address) String() string

String returns the address as a string.

func (Address) Valid

func (a Address) Valid() bool

Valid returns true if the address is well formed or false otherwise. An address is well formed if it is of the form: ConnType://NetworkAddress. ConnType must be one of the constants defined in this file, NetworkAddress must contain the IP address + Port number. The IP address is validated by net.ParseIP & the port must be included in the range [0;65536]. For example, "tls://192.168.1.10:5678".

type BlockingDispatcher

type BlockingDispatcher struct {
	sync.Mutex
	// contains filtered or unexported fields
}

BlockingDispatcher is a Dispatcher that simply calls `p.Process()` on a processor p each time it receives a message with `Dispatch`. It does *not* launch a go routine, or put the message in a queue, etc. It can be re-used for more complex dispatchers.

func NewBlockingDispatcher

func NewBlockingDispatcher() *BlockingDispatcher

NewBlockingDispatcher will return a new BlockingDispatcher.

func (*BlockingDispatcher) Dispatch

func (d *BlockingDispatcher) Dispatch(packet *Envelope) error

Dispatch calls the corresponding processor's method Process. It's a blocking call if the Processor is blocking.

func (*BlockingDispatcher) RegisterProcessor

func (d *BlockingDispatcher) RegisterProcessor(p Processor, msgType ...MessageTypeID)

RegisterProcessor saves the given processor in the dispatcher.

func (*BlockingDispatcher) RegisterProcessorFunc

func (d *BlockingDispatcher) RegisterProcessorFunc(msgType MessageTypeID, fn func(*Envelope))

RegisterProcessorFunc takes a func, creates a Processor struct around it and registers it to the dispatcher.

type Conn

type Conn interface {
	// Send a message through the connection.
	// obj should be a POINTER to the actual struct to send, or an interface.
	// It should not be a Golang type.
	// Returns the number of bytes sent and an error if any.
	Send(Message) (uint64, error)
	// Receive any message through the connection. It is a blocking call that
	// returns either when a message arrived or when Close() has been called, or
	// when a network error occurred.
	Receive() (*Envelope, error)
	// Close will close the connection. Implementations must take care that
	// Close() makes Receive() returns with an error, and any subsequent Send()
	// will return with an error. Calling Close() on a closed Conn will return
	// ErrClosed.
	Close() error
	IsClosed() bool

	// Type returns the type of this connection.
	Type() ConnType
	// Gives the address of the remote endpoint.
	Remote() Address
	// Returns the local address and port.
	Local() Address
	// Tx returns how many bytes this connection has written
	Tx() uint64
	// Rx returns how many bytes this connection has read
	Rx() uint64
}

Conn represents any communication between two hosts.

type ConnType

type ConnType string

ConnType represents the type of a Connection. The supported types are defined as constants of type ConnType.

type Dispatcher

type Dispatcher interface {
	// RegisterProcessor is called by a Processor so it can receive all messages
	// of type msgType. If given multiple msgType, the same processor will be
	// called for each of the msgType given.
	// **NOTE** In the current version, if a subsequent call to RegisterProcessor
	// happens for the same msgType, the latest Processor will be used; there
	// is no *copy* or *duplication* of messages.
	RegisterProcessor(p Processor, msgType ...MessageTypeID)
	// RegisterProcessorFunc enables to register directly a function that will
	// be called for each message of type msgType. It's a shorter way of
	// registering a Processor.
	RegisterProcessorFunc(MessageTypeID, func(*Envelope))
	// Dispatch will find the right processor to dispatch the packet to. The id
	// is the identity of the author / sender of the packet.
	// It can be called for example by the network layer.
	// If no processor is found for this message type, then an error is returned
	Dispatch(*Envelope) error
}

Dispatcher is an interface whose sole role is to distribute messages to the right Processor. No processing is done,i.e. no looking at packet content. Each Processor that wants to receive all messages of a specific type must register itself to the dispatcher using `RegisterProcessor()`. The network layer calls `Dispatch()` each time it receives a message, so the dispatcher is able to dispatch correctly to the corresponding Processor. Two Dispatchers are available:

  • BlockingDispatcher - waits for the return of the Processor before taking another message
  • RoutineDispatcher - starts every Processor in a go-routine

type Envelope

type Envelope struct {
	// The ServerIdentity of the remote peer we are talking to.
	// Basically, this means that when you open a new connection to someone, and
	// or listen to incoming connections, the network library will already
	// make some exchange between the two communicants so each knows the
	// ServerIdentity of the others.
	ServerIdentity *ServerIdentity
	// What kind of msg do we have
	MsgType MessageTypeID
	// A *pointer* to the underlying message
	Msg Message
	// which constructors are used
	Constructors protobuf.Constructors
}

Envelope is a container for any Message received through the network that contains the Message itself as well as some metadata such as the type and the sender. This is created by the network stack upon reception and is never transmitted.

type Host

type Host interface {
	Listener

	Connect(si *ServerIdentity) (Conn, error)
}

Host listens for a specific type of Conn and can Connect to specific types of Conn. It is used by the Router so the router can manage connections while being oblivious to which type of connections it's handling.

type KCPConn

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

KCPConn implements the Conn interface using plain, unencrypted KCP.

func NewKCPConn

func NewKCPConn(addr Address) (conn *KCPConn, err error)

NewKCPConn will open a KCPConn to the given address. In case of an error it returns a nil KCPConn and the error.

func (*KCPConn) Close

func (c *KCPConn) Close() error

Close the connection. Returns error if it couldn't close the connection.

func (*KCPConn) IsClosed

func (c *KCPConn) IsClosed() bool

IsClosed return connection closing

func (*KCPConn) Local

func (c *KCPConn) Local() Address

Local returns the local address and port.

func (*KCPConn) Receive

func (c *KCPConn) Receive() (env *Envelope, e error)

Receive get the bytes from the connection then decodes the buffer. It returns the Envelope containing the message, or EmptyEnvelope and an error if something wrong happened.

func (*KCPConn) Remote

func (c *KCPConn) Remote() Address

Remote returns the name of the peer at the end point of the connection.

func (*KCPConn) Rx

func (c *KCPConn) Rx() (out uint64)

Rx returns the rx counter

func (*KCPConn) Send

func (c *KCPConn) Send(msg Message) (uint64, error)

Send converts the NetworkMessage into an ApplicationMessage and sends it using send(). It returns the number of bytes sent and an error if anything was wrong.

func (*KCPConn) Tx

func (c *KCPConn) Tx() (out uint64)

Tx returns the tx counter

func (*KCPConn) Type

func (c *KCPConn) Type() ConnType

Type returns PlainKCP.

type KCPHost

type KCPHost struct {
	*KCPListener
	// contains filtered or unexported fields
}

KCPHost implements the Host interface using KCP connections.

func NewKCPHost

func NewKCPHost(sid *ServerIdentity) (*KCPHost, error)

NewKCPHost returns a new Host using KCP connection based type.

func NewKCPHostWithListenAddr

func NewKCPHostWithListenAddr(sid *ServerIdentity, listenAddr string) (*KCPHost, error)

NewKCPHostWithListenAddr returns a new Host using KCP connection based type listening on the given address.

func (*KCPHost) Connect

func (t *KCPHost) Connect(si *ServerIdentity) (Conn, error)

Connect can only connect to PlainKCP connections. It will return an error if it is not a PlainKCP-connection-type.

type KCPListener

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

KCPListener implements the Host-interface using Kcp as a communication channel.

func NewKCPListener

func NewKCPListener(addr Address) (*KCPListener, error)

NewKCPListener returns a KCPListener. This function binds globally using the port of 'addr'. It returns the listener and an error if one occurred during the binding. A subsequent call to Address() gives the actual listening address which is different if you gave it a ":0"-address.

func NewKCPListenerWithListenAddr

func NewKCPListenerWithListenAddr(addr Address, listenAddr string) (*KCPListener, error)

NewKCPListenerWithListenAddr returns a KCPListener. This function binds to the given 'listenAddr'. If it is empty, the function binds globally using the port of 'addr'. It returns the listener and an error if one occurred during the binding. A subsequent call to Address() gives the actual listening address which is different if you gave it a ":0"-address.

func (*KCPListener) Address

func (t *KCPListener) Address() Address

Address returns the listening address.

func (*KCPListener) Listen

func (t *KCPListener) Listen(fn func(Conn)) error

Listen starts to listen for incoming connections and calls fn for every connection-request it receives. If the connection is closed, an error will be returned.

func (*KCPListener) Listening

func (t *KCPListener) Listening() bool

Listening returns whether it's already listening.

func (*KCPListener) Stop

func (t *KCPListener) Stop() error

Stop the listener. It waits till all connections are closed and returned from. If there is no listener it will return an error.

type Listener

type Listener interface {
	// Listen for incoming connections.
	// Each time there is an incoming Conn, it calls the given
	// function in a go routine with the incoming Conn as parameter.
	// The call is blocking. If this listener is already Listening, Listen
	// should return an error.
	Listen(func(Conn)) error
	// Stop the listening. Implementations must take care of making
	// Stop() a blocking call. Stop() should return when the Listener really
	// has stopped listening, i.e. the call to Listen has returned. Calling twice
	// Stop() should return an error ErrClosed on the second call.
	Stop() error

	// A complete address including the type this listener is listening
	// to.
	Address() Address

	// Returns whether this listener is actually listening or not. This
	// function is mainly useful for tests where we need to make sure the
	// listening routine is started.
	Listening() bool
}

Listener is responsible for listening for incoming Conns on a particular address. It can only accept one type of incoming Conn.

type Message

type Message interface{}

Message is a type for any message that the user wants to send

type MessageTypeID

type MessageTypeID uuid.UUID

MessageTypeID is the ID used to uniquely identify different registered messages

func MessageType

func MessageType(msg Message) MessageTypeID

MessageType returns a Message's MessageTypeID if registered or ErrorType if the message has not been registered with RegisterMessage().

func RegisterMessage

func RegisterMessage(msg Message) MessageTypeID

RegisterMessage registers any struct or ptr and returns the corresponding MessageTypeID. Once a struct is registered, it can be sent and received by the network library.

func RegisterMessages

func RegisterMessages(msg ...Message) []MessageTypeID

RegisterMessages is a convenience function to register multiple messages together. It returns the MessageTypeIDs of the registered messages. If you give the same message more than once, it will register it only once, but return it's id as many times as it appears in the arguments.

func (MessageTypeID) Equal

func (mId MessageTypeID) Equal(mID2 MessageTypeID) bool

Equal returns true if and only if mID2 equals this MessageTypeID

func (MessageTypeID) IsNil

func (mId MessageTypeID) IsNil() bool

IsNil returns true iff the MessageTypeID is Nil

func (MessageTypeID) String

func (mId MessageTypeID) String() string

String returns the name of the structure if it is known, else it returns the hexadecimal value of the Id.

type Processor

type Processor interface {
	// Process takes a received Envelope.
	Process(*Envelope)
}

Processor is an abstraction to represent any object that want to process messages. It is used in conjunction with Dispatcher: A processor must register itself to a Dispatcher so the Dispatcher will dispatch every messages asked for to the Processor.

type Router

type Router struct {
	// id is our own ServerIdentity
	ServerIdentity *ServerIdentity

	// Dispatcher is used to dispatch incoming message to the right recipient
	Dispatcher

	sync.Mutex

	// This field should only be set during testing. It disables an important
	// log message meant to discourage KCP connections.
	UnauthOk bool
	// contains filtered or unexported fields
}

Router handles all networking operations such as:

  • listening to incoming connections using a host.Listener method
  • opening up new connections using host.Connect method
  • dispatching incoming message using a Dispatcher
  • dispatching outgoing message maintaining a translation between ServerIdentity <-> address
  • managing the re-connections of non-working Conn

Most caller should use the creation function like NewKCPRouter(...), NewLocalRouter(...) then use the Host such as:

router.Start() // will listen for incoming Conn and block
router.Stop() // will stop the listening and the managing of all Conn

func NewKCPRouter

func NewKCPRouter(sid *ServerIdentity) (*Router, error)

NewKCPRouter returns a new Router using KCPHost as the underlying Host.

func NewKCPRouterWithListenAddr

func NewKCPRouterWithListenAddr(sid *ServerIdentity, listenAddr string) (*Router, error)

NewKCPRouterWithListenAddr returns a new Router using KCPHost with the given listen address as the underlying Host.

func NewRouter

func NewRouter(own *ServerIdentity, h Host) *Router

NewRouter returns a new Router attached to a ServerIdentity and the host we want to use.

func (*Router) AddErrorHandler

func (r *Router) AddErrorHandler(errorHandler func(*ServerIdentity))

AddErrorHandler adds a network error handler function for this router. The functions will be called on network error (e.g. Timeout, Connection Closed, or EOF) with the identity of the faulty remote host as 1st parameter.

func (*Router) AdjustConnect

func (r *Router) AdjustConnect(mlist map[ServerIdentityID]bool)

AdjustConnect close all remote connects that not in mlist

func (*Router) CloseConnectByID

func (r *Router) CloseConnectByID(id ServerIdentityID)

func (*Router) Closed

func (r *Router) Closed() bool

Closed returns true if the router is closed (or is closing). For a router to be closed means that a call to Stop() must have been made.

func (*Router) GetBlocks

func (r *Router) GetBlocks(e *ServerIdentity) int

func (*Router) Listening

func (r *Router) Listening() bool

Listening returns true if this router is started.

func (*Router) Pause

func (r *Router) Pause()

Pause casues the router to stop after reading the next incoming message. It sleeps until it is woken up by Unpause. For testing use only.

func (*Router) Rx

func (r *Router) Rx() uint64

Rx implements monitor/CounterIO It returns the Rx for all connections managed by this router

func (*Router) Send

func (r *Router) Send(e *ServerIdentity, msg Message, bForeConnect bool) (uint64, error)

Send sends to an ServerIdentity without wrapping the msg into a ProtocolMsg

func (*Router) Start

func (r *Router) Start()

Start the listening routine of the underlying Host. This is a blocking call until r.Stop() is called.

func (*Router) Stop

func (r *Router) Stop() error

Stop the listening routine, and stop any routine of handling connections. Calling r.Start(), then r.Stop() then r.Start() again leads to an undefined behaviour. Callers should most of the time re-create a fresh Router.

func (*Router) Tx

func (r *Router) Tx() uint64

Tx implements monitor/CounterIO It returns the Tx for all connections managed by this router

func (*Router) Unpause

func (r *Router) Unpause()

Unpause reverses a previous call to Pause. All paused connections are closed and the Router is again ready to process messages normally. For testing use only.

type RoutineDispatcher

type RoutineDispatcher struct {
	*BlockingDispatcher
	// contains filtered or unexported fields
}

RoutineDispatcher dispatches messages to the Processors in a go routine. RoutineDispatcher creates one go routine per messages it receives.

func NewRoutineDispatcher

func NewRoutineDispatcher() *RoutineDispatcher

NewRoutineDispatcher returns a fresh RoutineDispatcher

func (*RoutineDispatcher) Dispatch

func (d *RoutineDispatcher) Dispatch(packet *Envelope) error

Dispatch implements the Dispatcher interface. It will give the packet to the right Processor in a go routine.

func (*RoutineDispatcher) GetRoutines

func (d *RoutineDispatcher) GetRoutines() int

GetRoutines returns how many routines are waiting.

type ServerIdentity

type ServerIdentity struct {
	// The ServerIdentityID corresponding to that address key
	ID ServerIdentityID
	// A slice of addresses of where that Id might be found
	Address Address
	// Description of the server
	Description string
}

ServerIdentity is used to represent a Server in the whole internet. It's based on a address key, and there can be one or more addresses to contact it.

func NewServerIdentity

func NewServerIdentity(address string) *ServerIdentity

NewServerIdentity creates a new ServerIdentity based on a address key and with a slice of IP-addresses where to find that entity. The Id is based on a version5-UUID which can include a URL that is based on it's address key.

func (*ServerIdentity) String

func (si *ServerIdentity) String() string

type ServerIdentityID

type ServerIdentityID uuid.UUID

ServerIdentityID uniquely identifies an ServerIdentity struct

func (ServerIdentityID) Equal

func (eId ServerIdentityID) Equal(other ServerIdentityID) bool

Equal returns true if both ServerIdentityID are equal or false otherwise.

func (ServerIdentityID) IsNil

func (eId ServerIdentityID) IsNil() bool

IsNil returns true iff the ServerIdentityID is Nil

func (ServerIdentityID) String

func (eId ServerIdentityID) String() string

String returns a canonical representation of the ServerIdentityID.

type Size

type Size uint32

Size is a type to reprensent the size that is sent before every packet to correctly decode it.

Jump to

Keyboard shortcuts

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