netcode

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2020 License: BSD-3-Clause Imports: 16 Imported by: 0

README

GoDoc Build Status

Go implementation of netcode.io

This is the main repository for the Go implementation of netcode.io.

Dependencies

The only dependency is golang.org/x/crypto/chacha20poly1305 and it has been vendored so it should not be necessary to retrieve any packages outside of netcode.

Testing

To run tests for this package run the following from the package directory:

$ go test

Updating

To ensure the package is up-to-date run the following from the package directory:

go get -u

Author

Documentation

Index

Constants

View Source
const (
	StateTokenExpired               ClientState = -6
	StateInvalidConnectToken                    = -5
	StateConnectionTimedOut                     = -4
	StateConnectionResponseTimedOut             = -3
	StateConnectionRequestTimedOut              = -2
	StateConnectionDenied                       = -1
	StateDisconnected                           = 0
	StateSendingConnectionRequest               = 1
	StateSendingConnectionResponse              = 2
	StateConnected                              = 3
)
View Source
const (
	ADDRESS_NONE = iota
	ADDRESS_IPV4
	ADDRESS_IPV6
)

ip types used in serialization of server addresses

View Source
const (
	SOCKET_RCVBUF_SIZE = 2048 * 2048
	SOCKET_SNDBUF_SIZE = 2048 * 2048
)
View Source
const (

	// SizeUint8 is the byte size of a uint8.
	SizeUint8 = 1
	// SizeUint16 is the byte size of a uint16.
	SizeUint16 = 2
	// SizeUint32 is the byte size of a uint32.
	SizeUint32 = 4
	// SizeUint64 is the byte size of a uint64.
	SizeUint64 = 8

	// SizeInt8 is the byte size of a int8.
	SizeInt8 = 1
	// SizeInt16 is the byte size of a int16.
	SizeInt16 = 2
	// SizeInt32 is the byte size of a int32.
	SizeInt32 = 4
	// SizeInt64 is the byte size of a int64.
	SizeInt64 = 8

	// SizeFloat32 is the byte size of a float32.
	SizeFloat32 = 4
	// SizeFloat64 is the byte size of a float64.
	SizeFloat64 = 8

	// SizeByte is the byte size of a byte.
	// The `byte` type is aliased (by Go definition) to uint8.
	SizeByte = 1

	// SizeBool is the byte size of a bool.
	// The `bool` type is aliased (by flatbuffers convention) to uint8.
	SizeBool = 1

	// SizeSOffsetT is the byte size of an SOffsetT.
	// The `SOffsetT` type is aliased (by flatbuffers convention) to int32.
	SizeSOffsetT = 4
	// SizeUOffsetT is the byte size of an UOffsetT.
	// The `UOffsetT` type is aliased (by flatbuffers convention) to uint32.
	SizeUOffsetT = 4
	// SizeVOffsetT is the byte size of an VOffsetT.
	// The `VOffsetT` type is aliased (by flatbuffers convention) to uint16.
	SizeVOffsetT = 2
)
View Source
const CHALLENGE_TOKEN_BYTES = 300
View Source
const CLIENT_MAX_RECEIVE_PACKETS = 64
View Source
const CONNECT_TOKEN_BYTES = 2048

number of bytes for connect tokens

View Source
const CONNECT_TOKEN_PRIVATE_BYTES = 1024
View Source
const ConnectionNumPackets = ConnectionDisconnect + 1

not a packet type, but value is last packetType+1

View Source
const EPSILON float64 = 0.000001
View Source
const KEY_BYTES = 32
View Source
const MAC_BYTES = 16
View Source
const MAX_ADDRESS_STRING_LENGTH = 256
View Source
const MAX_PACKET_BYTES = 1220
View Source
const MAX_PAYLOAD_BYTES = 1200
View Source
const MAX_SERVERS_PER_CONNECT = 32
View Source
const MAX_SERVER_PACKETS = 64
View Source
const NONCE_BYTES = 8
View Source
const NUM_DISCONNECT_PACKETS = 10 // number of disconnect packets the client/server should send when disconnecting
View Source
const PACKET_QUEUE_SIZE = 256
View Source
const PACKET_SEND_RATE = 20.0
View Source
const REPLAY_PROTECTION_BUFFER_SIZE = 256
View Source
const TIMEOUT_SECONDS = 5 // default timeout for clients
View Source
const USER_DATA_BYTES = 256
View Source
const VERSION_INFO = "NETCODE 1.01\x00"
View Source
const VERSION_INFO_BYTES = 13

Variables

View Source
var (
	ErrChallengePacketDecryptedDataSize  = errors.New("ignored connection challenge packet. decrypted packet data is wrong size")
	ErrChallengePacketTokenData          = errors.New("error reading challenge token data")
	ErrChallengePacketTokenSequence      = errors.New("error reading challenge token sequence")
	ErrClientNotConnected                = errors.New("client not connected, unable to send packet")
	ErrDecryptPacketPayloadTooSmall      = errors.New("ignored encrypted packet. encrypted payload is too small")
	ErrDeniedPacketDecryptedDataSize     = errors.New("ignored connection denied packet. decrypted packet data is wrong size")
	ErrDisconnectPacketDecryptedDataSize = errors.New("ignored connection denied packet. decrypted packet data is wrong size")
	ErrEmptyPacketKey                    = errors.New("empty packet key")
	ErrEmptyServers                      = errors.New("empty servers")
	ErrEncryptedPacketBufferTooSmall     = errors.New("ignored encrypted packet. buffer is too small for sequence bytes + encryption mac")
	ErrEncryptedPacketSequenceOutOfRange = errors.New("ignored encrypted packet. sequence bytes is out of range [1,8]")
	ErrEncryptedPacketTooSmall           = errors.New("ignored encrypted packet. packet is too small to be valid")
	ErrExceededServerNumber              = errors.New("invalid server address, exceeded # of servers")
	ErrExpiredTokenTimestamp             = errors.New("expire timestamp is > create timestamp")
	ErrInvalidBufferLength               = errors.New("invalid buffer length")
	ErrInvalidBufferSize                 = errors.New("invalid buffer size written")
	ErrInvalidIPAddress                  = errors.New("invalid ip address")
	ErrInvalidPacket                     = errors.New("invalid packet")
	ErrInvalidPort                       = errors.New("invalid port")
	ErrInvalidSequenceBytes              = errors.New("invalid sequence bytes, must be between [1-8]")
	ErrInvalidTokenPrivateByteSize       = errors.New("error in encrypt invalid token private byte size")
	ErrKeepAlivePacketClientIndex        = errors.New("error reading keepalive client index")
	ErrKeepAlivePacketDecryptedDataSize  = errors.New("ignored connection keep alive packet. decrypted packet data is wrong size")
	ErrKeepAlivePacketMaxClients         = errors.New("error reading keepalive max clients")
	ErrPacketHandlerBeforeListen         = errors.New("packet handler must be set before calling listen")
	ErrPacketSizeMax                     = errors.New("packet size was > maxBytes")
	ErrPayloadPacketTooLarge             = errors.New("payload packet: payload is too large")
	ErrPayloadPacketTooSmall             = errors.New("payload packet: payload is too small")
	ErrReadingUserData                   = errors.New("error reading user data")
	ErrRequestBadPacketLength            = errors.New("request packet: bad packet length")
	ErrRequestPacketBadProtocolId        = errors.New("request packet: wrong protocol id")
	ErrRequestPacketBadVersionInfo       = errors.New("request packet: bad version info did not match")
	ErrRequestPacketBadVersionInfoBytes  = errors.New("request packet: bad version info invalid bytes returned")
	ErrRequestPacketBufferInvalidLength  = errors.New("invalid length of packet buffer read")
	ErrRequestPacketConnectTokenExpired  = errors.New("request packet: connect token expired")
	ErrRequestPacketNoPrivateKey         = errors.New("request packet: no private key")
	ErrRequestPacketTypeNotAllowed       = errors.New("request packet: packet type is not allowed")
	ErrResponsePacketDecryptedDataSize   = errors.New("challenge response packet: decrypted packet data is wrong size")
	ErrResponsePacketTokenData           = errors.New("error reading challenge token data")
	ErrResponsePacketTokenSequence       = errors.New("error reading challenge token sequence")
	ErrServerNotRunning                  = errors.New("server is not running")
	ErrServerShutdown                    = errors.New("server shutdown")
	ErrSocketZeroRecv                    = errors.New("socket error: 0 byte length recv'd")
	ErrTooManyServers                    = errors.New("too many servers")
	ErrUnknownIPAddress                  = errors.New("unknown ip address")
	ErrWriteClosedSocket                 = errors.New("unable to write, socket has been closed")
)

Functions

func DecryptAead

func DecryptAead(message []byte, additional, nonce, key []byte) ([]byte, error)

Decrypts the message with the nonce and key and optional additional buffer returning a copy byte slice

func DecryptChallengeToken

func DecryptChallengeToken(tokenBuffer []byte, sequence uint64, key []byte) ([]byte, error)

Decrypts the TokenData buffer with the sequence nonce and provided key, updating the internal TokenData buffer

func EncryptAead

func EncryptAead(message []byte, additional, nonce, key []byte) error

Encrypts the message in place with the nonce and key and optional additional buffer

func EncryptChallengeToken

func EncryptChallengeToken(tokenBuffer []byte, sequence uint64, key []byte) error

Encrypts the TokenData buffer with the sequence nonce and provided key

func GenerateKey

func GenerateKey() ([]byte, error)

Generates a random key of KEY_BYTES

func RandomBytes

func RandomBytes(bytes int) ([]byte, error)

Generates random bytes

Types

type Buffer

type Buffer struct {
	Buf []byte // the backing byte slice
	Pos int    // current position in read/write
}

Buffer is a helper struct for serializing and deserializing as the caller does not need to externally manage where in the buffer they are currently reading or writing to.

func NewBuffer

func NewBuffer(size int) *Buffer

Creates a new Buffer with a backing byte slice of the provided size

func NewBufferFromBytes

func NewBufferFromBytes(buf []byte) *Buffer

Creates a new buffer from a byte slice

func NewBufferFromRef

func NewBufferFromRef(buf []byte) *Buffer

Creates a new Buffer using the original backing slice

func (*Buffer) Bytes

func (b *Buffer) Bytes() []byte

Returns the backing byte slice

func (*Buffer) Copy

func (b *Buffer) Copy() *Buffer

Returns a copy of Buffer

func (*Buffer) GetByte

func (b *Buffer) GetByte() (byte, error)

GetByte decodes a little-endian byte

func (*Buffer) GetBytes

func (b *Buffer) GetBytes(length int) ([]byte, error)

GetBytes returns a byte slice possibly smaller than length if bytes are not available from the reader.

func (*Buffer) GetInt16

func (b *Buffer) GetInt16() (int16, error)

GetInt16 decodes a little-endian int16 from the buffer

func (*Buffer) GetInt32

func (b *Buffer) GetInt32() (int32, error)

GetInt32 decodes a little-endian int32 from the buffer

func (*Buffer) GetInt64

func (b *Buffer) GetInt64() (int64, error)

GetInt64 decodes a little-endian int64 from the buffer

func (*Buffer) GetInt8

func (b *Buffer) GetInt8() (int8, error)

GetInt8 decodes a little-endian int8 from the buffer

func (*Buffer) GetUint16

func (b *Buffer) GetUint16() (uint16, error)

GetUint16 decodes a little-endian uint16 from the buffer

func (*Buffer) GetUint32

func (b *Buffer) GetUint32() (uint32, error)

GetUint32 decodes a little-endian uint32 from the buffer

func (*Buffer) GetUint64

func (b *Buffer) GetUint64() (uint64, error)

GetUint64 decodes a little-endian uint64 from the buffer

func (*Buffer) GetUint8

func (b *Buffer) GetUint8() (uint8, error)

GetUint8 decodes a little-endian uint8 from the buffer

func (*Buffer) Len

func (b *Buffer) Len() int

Gets the length of the backing byte slice

func (*Buffer) Reset

func (b *Buffer) Reset()

Resets the position back to beginning of buffer

func (*Buffer) WriteByte

func (b *Buffer) WriteByte(n byte)

WriteByte encodes a little-endian uint8 into the buffer.

func (*Buffer) WriteBytes

func (b *Buffer) WriteBytes(src []byte)

WriteBytes encodes a little-endian byte slice into the buffer

func (*Buffer) WriteBytesN

func (b *Buffer) WriteBytesN(src []byte, length int)

WriteBytes encodes a little-endian byte slice into the buffer

func (*Buffer) WriteFloat32

func (b *Buffer) WriteFloat32(n float32)

WriteFloat32 encodes a little-endian float32 into the buffer.

func (*Buffer) WriteFloat64

func (b *Buffer) WriteFloat64(buf []byte, n float64)

WriteFloat64 encodes a little-endian float64 into the buffer.

func (*Buffer) WriteInt16

func (b *Buffer) WriteInt16(n int16)

WriteInt16 encodes a little-endian int16 into the buffer.

func (*Buffer) WriteInt32

func (b *Buffer) WriteInt32(n int32)

WriteInt32 encodes a little-endian int32 into the buffer.

func (*Buffer) WriteInt64

func (b *Buffer) WriteInt64(n int64)

WriteInt64 encodes a little-endian int64 into the buffer.

func (*Buffer) WriteInt8

func (b *Buffer) WriteInt8(n int8)

WriteInt8 encodes a little-endian int8 into the buffer.

func (*Buffer) WriteUint16

func (b *Buffer) WriteUint16(n uint16)

WriteUint16 encodes a little-endian uint16 into the buffer.

func (*Buffer) WriteUint32

func (b *Buffer) WriteUint32(n uint32)

WriteUint32 encodes a little-endian uint32 into the buffer.

func (*Buffer) WriteUint64

func (b *Buffer) WriteUint64(n uint64)

WriteUint64 encodes a little-endian uint64 into the buffer.

func (*Buffer) WriteUint8

func (b *Buffer) WriteUint8(n uint8)

WriteUint8 encodes a little-endian uint8 into the buffer.

type ChallengePacket

type ChallengePacket struct {
	ChallengeTokenSequence uint64
	ChallengeTokenData     []byte
	// contains filtered or unexported fields
}

Challenge packet containing token data and the sequence id used

func (*ChallengePacket) GetType

func (p *ChallengePacket) GetType() PacketType

func (*ChallengePacket) Read

func (p *ChallengePacket) Read(packetData []byte, packetLen int, protocolId, currentTimestamp uint64, readPacketKey, privateKey, allowedPackets []byte, replayProtection *ReplayProtection) error

func (*ChallengePacket) Sequence

func (p *ChallengePacket) Sequence() uint64

func (*ChallengePacket) Write

func (p *ChallengePacket) Write(buf []byte, protocolId, sequence uint64, writePacketKey []byte) (int, error)

type ChallengeToken

type ChallengeToken struct {
	ClientId  uint64  // the clientId associated with this token
	UserData  *Buffer // the userdata payload
	TokenData *Buffer // the serialized payload container
}

Challenge tokens are used in certain packet types

func NewChallengeToken

func NewChallengeToken(clientId uint64) *ChallengeToken

Creates a new empty challenge token with only the clientId set

func ReadChallengeToken

func ReadChallengeToken(buffer []byte) (*ChallengeToken, error)

Generates a new ChallengeToken from the provided buffer byte slice. Only sets the ClientId and UserData buffer.

func (*ChallengeToken) Write

func (t *ChallengeToken) Write(userData []byte) []byte

Serializes the client id and userData, also sets the UserData buffer.

type Client

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

func NewClient

func NewClient(connectToken *ConnectToken, metricsRegistry metrics.Registry) *Client

func (*Client) Close

func (c *Client) Close() error

func (*Client) Connect

func (c *Client) Connect(localPort int) error

func (*Client) Disconnect

func (c *Client) Disconnect(reason ClientState, sendDisconnect bool) error

func (*Client) GetState

func (c *Client) GetState() ClientState

func (*Client) LocalAddr

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

func (*Client) OnPacketData

func (c *Client) OnPacketData(packetData []byte, from *net.UDPAddr)

func (*Client) RecvData

func (c *Client) RecvData() ([]byte, uint64)

func (*Client) RemoteAddr

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

func (*Client) Reset

func (c *Client) Reset()

func (*Client) SendData

func (c *Client) SendData(payloadData []byte) error

func (*Client) SetId

func (c *Client) SetId(id uint64)

func (*Client) Update

func (c *Client) Update(t float64)

type ClientInstance

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

func NewClientInstance

func NewClientInstance() *ClientInstance

func (*ClientInstance) Clear

func (c *ClientInstance) Clear()

func (*ClientInstance) SendPacket

func (c *ClientInstance) SendPacket(packet Packet, writePacketKey []byte, serverTime float64) error

type ClientManager

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

func NewClientManager

func NewClientManager(timeout float64, maxClients int) *ClientManager

func (*ClientManager) AddEncryptionMapping

func (m *ClientManager) AddEncryptionMapping(connectToken *ConnectTokenPrivate, addr *net.UDPAddr, serverTime, expireTime float64) bool

Adds a new encryption mapping of client/server keys.

func (*ClientManager) CheckTimeouts

func (m *ClientManager) CheckTimeouts(serverTime float64)

Checks and disconnects any clients that have timed out.

func (*ClientManager) ConnectClient

func (m *ClientManager) ConnectClient(addr *net.UDPAddr, challengeToken *ChallengeToken) *ClientInstance

Initializes the client with the clientId

func (*ClientManager) ConnectedClientCount

func (m *ClientManager) ConnectedClientCount() int

func (*ClientManager) ConnectedClients

func (m *ClientManager) ConnectedClients() []uint64

Returns the clientIds of the connected clients. To avoid allocating a buffer everytime this is called we simply re-add all connected clients to the connectedClientIds buffer and return the slice of how many we were able to add.

func (*ClientManager) DisconnectClient

func (m *ClientManager) DisconnectClient(clientIndex int, sendDisconnect bool, serverTime float64)

Disconnects the client referenced by the provided clientIndex.

func (*ClientManager) FindClientIndexByAddress

func (m *ClientManager) FindClientIndexByAddress(addr *net.UDPAddr) int

Finds the client index referenced by the provided UDPAddr.

func (*ClientManager) FindClientIndexById

func (m *ClientManager) FindClientIndexById(clientId uint64) int

Finds the client index via the provided clientId.

func (*ClientManager) FindEncryptionEntryIndex

func (m *ClientManager) FindEncryptionEntryIndex(addr *net.UDPAddr, serverTime float64) int

Finds an encryption entry index via the provided UDPAddr.

func (*ClientManager) FindEncryptionIndexByClientIndex

func (m *ClientManager) FindEncryptionIndexByClientIndex(clientIndex int) int

Finds the encryption index via the provided clientIndex, returns -1 if not found.

func (*ClientManager) FindFreeClientIndex

func (m *ClientManager) FindFreeClientIndex() int

func (*ClientManager) FindOrAddTokenEntry

func (m *ClientManager) FindOrAddTokenEntry(connectTokenMac []byte, addr *net.UDPAddr, serverTime float64) bool

Finds or adds a token entry to our token entry slice.

func (*ClientManager) GetEncryptionEntryRecvKey

func (m *ClientManager) GetEncryptionEntryRecvKey(index int) []byte

Returns the encryption recv key.

func (*ClientManager) GetEncryptionEntrySendKey

func (m *ClientManager) GetEncryptionEntrySendKey(index int) []byte

Returns the encryption send key.

func (*ClientManager) RemoveEncryptionEntry

func (m *ClientManager) RemoveEncryptionEntry(addr *net.UDPAddr, serverTime float64) bool

Removes the encryption entry for this UDPAddr.

func (*ClientManager) SendKeepAlives

func (m *ClientManager) SendKeepAlives(serverTime float64)

Send keep alives to all connected clients.

func (*ClientManager) SetEncryptionEntryExpiration

func (m *ClientManager) SetEncryptionEntryExpiration(encryptionIndex int, expireTime float64) bool

Sets the expiration for this encryption entry.

func (*ClientManager) TouchEncryptionEntry

func (m *ClientManager) TouchEncryptionEntry(encryptionIndex int, addr *net.UDPAddr, serverTime float64) bool

Update the encryption entry for the provided encryption index.

type ClientState

type ClientState int8

type ConnectToken

type ConnectToken struct {
	VersionInfo     []byte               // the version information for client <-> server communications
	ProtocolId      uint64               // protocol id for communications
	CreateTimestamp uint64               // when this token was created
	ExpireTimestamp uint64               // when this token expires
	Sequence        uint64               // the sequence id
	PrivateData     *ConnectTokenPrivate // reference to the private parts of this connect token
	// contains filtered or unexported fields
}

Token used for connecting

func NewConnectToken

func NewConnectToken() *ConnectToken

Create a new empty token and empty private token

func ReadConnectToken

func ReadConnectToken(tokenBuffer []byte) (*ConnectToken, error)

Takes in a slice of decrypted connect token bytes and generates a new ConnectToken. Note that the ConnectTokenPrivate is still encrypted at this point.

func (*ConnectToken) Generate

func (token *ConnectToken) Generate(clientId uint64, serverAddrs []net.UDPAddr, versionInfo string, protocolId uint64, expireSeconds uint64, timeoutSeconds int32, sequence uint64, userData, privateKey []byte) error

Generates the token and private token data with the supplied config values and sequence id. This will also write and encrypt the private token

func (*ConnectToken) GenerateShared

func (shared *ConnectToken) GenerateShared() error

func (*ConnectToken) ReadShared

func (shared *ConnectToken) ReadShared(buffer *Buffer) error

Reads and validates the servers, client <-> server keys.

func (*ConnectToken) Write

func (token *ConnectToken) Write() ([]byte, error)

Writes the ConnectToken and previously encrypted ConnectTokenPrivate data to a byte slice

func (*ConnectToken) WriteShared

func (shared *ConnectToken) WriteShared(buffer *Buffer) error

Writes the servers and client <-> server keys to the supplied buffer

type ConnectTokenPrivate

type ConnectTokenPrivate struct {
	ClientId uint64 // id for this token
	UserData []byte // used to store user data

	TokenData *Buffer // used to store the serialized/encrypted buffer
	// contains filtered or unexported fields
}

The private parts of a connect token

func NewConnectTokenPrivate

func NewConnectTokenPrivate(clientId uint64, timeoutSeconds int32, serverAddrs []net.UDPAddr, userData []byte) *ConnectTokenPrivate

Create a new connect token private with an empty TokenData buffer

func NewConnectTokenPrivateEncrypted

func NewConnectTokenPrivateEncrypted(buffer []byte) *ConnectTokenPrivate

Create a new connect token private with an pre-set, encrypted buffer Caller is expected to call Decrypt() and Read() to set the instances properties

func (*ConnectTokenPrivate) Buffer

func (p *ConnectTokenPrivate) Buffer() []byte

Helper to return the internal []byte of the private data

func (*ConnectTokenPrivate) Decrypt

func (p *ConnectTokenPrivate) Decrypt(protocolId, expireTimestamp, sequence uint64, privateKey []byte) ([]byte, error)

Decrypts the internal TokenData buffer, assumes that TokenData has been populated with the encrypted data (most likely via NewConnectTokenPrivateEncrypted(...)). Optionally returns the decrypted buffer to caller.

func (*ConnectTokenPrivate) Encrypt

func (p *ConnectTokenPrivate) Encrypt(protocolId, expireTimestamp, sequence uint64, privateKey []byte) error

Encrypts, in place, the TokenData buffer, assumes Write() has already been called.

func (*ConnectTokenPrivate) Generate

func (p *ConnectTokenPrivate) Generate() error

func (*ConnectTokenPrivate) GenerateShared

func (shared *ConnectTokenPrivate) GenerateShared() error

func (*ConnectTokenPrivate) Mac

func (p *ConnectTokenPrivate) Mac() []byte

Returns the message authentication code for the encrypted buffer by splicing the token data, returns an empty byte slice if the tokendata buffer is empty/less than MAC_BYTES

func (*ConnectTokenPrivate) Read

func (p *ConnectTokenPrivate) Read() error

Reads the token properties from the internal TokenData buffer.

func (*ConnectTokenPrivate) ReadShared

func (shared *ConnectTokenPrivate) ReadShared(buffer *Buffer) error

Reads and validates the servers, client <-> server keys.

func (*ConnectTokenPrivate) Write

func (p *ConnectTokenPrivate) Write() ([]byte, error)

Writes the token data to our TokenData buffer and alternatively returns the buffer to caller.

func (*ConnectTokenPrivate) WriteShared

func (shared *ConnectTokenPrivate) WriteShared(buffer *Buffer) error

Writes the servers and client <-> server keys to the supplied buffer

type Context

type Context struct {
	WritePacketKey []byte
	ReadPacketKey  []byte
}

type DeniedPacket

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

Denied packet type, contains no information

func (*DeniedPacket) GetType

func (p *DeniedPacket) GetType() PacketType

func (*DeniedPacket) Read

func (p *DeniedPacket) Read(packetData []byte, packetLen int, protocolId, currentTimestamp uint64, readPacketKey, privateKey, allowedPackets []byte, replayProtection *ReplayProtection) error

func (*DeniedPacket) Sequence

func (p *DeniedPacket) Sequence() uint64

func (*DeniedPacket) Write

func (p *DeniedPacket) Write(buf []byte, protocolId, sequence uint64, writePacketKey []byte) (int, error)

type DisconnectPacket

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

Signals to server/client to disconnect, contains no data.

func (*DisconnectPacket) GetType

func (p *DisconnectPacket) GetType() PacketType

func (*DisconnectPacket) Read

func (p *DisconnectPacket) Read(packetData []byte, packetLen int, protocolId, currentTimestamp uint64, readPacketKey, privateKey, allowedPackets []byte, replayProtection *ReplayProtection) error

func (*DisconnectPacket) Sequence

func (p *DisconnectPacket) Sequence() uint64

func (*DisconnectPacket) Write

func (p *DisconnectPacket) Write(buf []byte, protocolId, sequence uint64, writePacketKey []byte) (int, error)

type KeepAlivePacket

type KeepAlivePacket struct {
	ClientIndex uint32
	MaxClients  uint32
	// contains filtered or unexported fields
}

used for heart beats

func (*KeepAlivePacket) GetType

func (p *KeepAlivePacket) GetType() PacketType

func (*KeepAlivePacket) Read

func (p *KeepAlivePacket) Read(packetData []byte, packetLen int, protocolId, currentTimestamp uint64, readPacketKey, privateKey, allowedPackets []byte, replayProtection *ReplayProtection) error

func (*KeepAlivePacket) Sequence

func (p *KeepAlivePacket) Sequence() uint64

func (*KeepAlivePacket) Write

func (p *KeepAlivePacket) Write(buf []byte, protocolId, sequence uint64, writePacketKey []byte) (int, error)

type NetcodeConn

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

func NewNetcodeConn

func NewNetcodeConn() *NetcodeConn

func (*NetcodeConn) Close

func (c *NetcodeConn) Close() error

func (*NetcodeConn) Dial

func (c *NetcodeConn) Dial(address *net.UDPAddr, localPort int) error

func (*NetcodeConn) Listen

func (c *NetcodeConn) Listen(address *net.UDPAddr) error

func (*NetcodeConn) LocalAddr

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

LocalAddr returns the local network address.

func (*NetcodeConn) RemoteAddr

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

RemoteAddr returns the remote network address.

func (*NetcodeConn) SetReadBuffer

func (c *NetcodeConn) SetReadBuffer(bytes int)

func (*NetcodeConn) SetRecvHandler

func (c *NetcodeConn) SetRecvHandler(recvHandlerFn NetcodeRecvHandler)

func (*NetcodeConn) SetWriteBuffer

func (c *NetcodeConn) SetWriteBuffer(bytes int)

func (*NetcodeConn) Write

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

func (*NetcodeConn) WriteTo

func (c *NetcodeConn) WriteTo(b []byte, to *net.UDPAddr) (int, error)

type NetcodeData

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

type NetcodeRecvHandler

type NetcodeRecvHandler func(data *NetcodeData)

type Packet

type Packet interface {
	GetType() PacketType                                                                                                                                                    // The type of packet
	Sequence() uint64                                                                                                                                                       // sequence number of this packet, if it supports it                                                                                                                                           // returns the packet type
	Write(buf []byte, protocolId, sequence uint64, writePacketKey []byte) (int, error)                                                                                      // writes and encrypts the packet data to the supplied buffer.
	Read(packetData []byte, packetLen int, protocolId, currentTimestamp uint64, readPacketKey, privateKey, allowedPackets []byte, replayProtection *ReplayProtection) error // reads in and decrypts from the supplied buffer to set the packet properties
}

Packet interface supporting reading and writing.

func NewPacket

func NewPacket(packetBuffer []byte) Packet

Returns the type of packet given packetbuffer by peaking the packet type

type PacketQueue

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

func NewPacketQueue

func NewPacketQueue(queueSize int) *PacketQueue

func (*PacketQueue) Clear

func (q *PacketQueue) Clear()

func (*PacketQueue) Pop

func (q *PacketQueue) Pop() Packet

func (*PacketQueue) Push

func (q *PacketQueue) Push(packet Packet) int

type PacketType

type PacketType uint8

Used for determining the type of packet, part of the serialization protocol

const (
	ConnectionRequest PacketType = iota
	ConnectionDenied
	ConnectionChallenge
	ConnectionResponse
	ConnectionKeepAlive
	ConnectionPayload
	ConnectionDisconnect
)

func (PacketType) Peek

func (p PacketType) Peek(packetBuffer []byte) PacketType

type PayloadPacket

type PayloadPacket struct {
	PayloadBytes uint32
	PayloadData  []byte
	// contains filtered or unexported fields
}

Contains user supplied payload data between server <-> client

func NewPayloadPacket

func NewPayloadPacket(payloadData []byte) *PayloadPacket

Helper function to create a new payload packet with the supplied buffer

func (*PayloadPacket) GetType

func (p *PayloadPacket) GetType() PacketType

func (*PayloadPacket) Read

func (p *PayloadPacket) Read(packetData []byte, packetLen int, protocolId, currentTimestamp uint64, readPacketKey, privateKey, allowedPackets []byte, replayProtection *ReplayProtection) error

func (*PayloadPacket) Sequence

func (p *PayloadPacket) Sequence() uint64

func (*PayloadPacket) Write

func (p *PayloadPacket) Write(buf []byte, protocolId, sequence uint64, writePacketKey []byte) (int, error)

type ReplayProtection

type ReplayProtection struct {
	MostRecentSequence uint64   // last sequence recv'd
	ReceivedPacket     []uint64 // slice of REPLAY_PROTECTION_BUFFER_SIZE worth of packet sequences
}

Our type to hold replay protection of packet sequences

func NewReplayProtection

func NewReplayProtection() *ReplayProtection

Initializes a new ReplayProtection with the ReceivedPacket buffer elements all set to 0xFFFFFFFFFFFFFFFF

func (*ReplayProtection) AlreadyReceived

func (r *ReplayProtection) AlreadyReceived(sequence uint64) bool

Tests that the sequence has not already been recv'd, adding it to the buffer if it's new.

func (*ReplayProtection) Reset

func (r *ReplayProtection) Reset()

Clears out the most recent sequence and resets the entire packet buffer to 0xFFFFFFFFFFFFFFFF

type RequestPacket

type RequestPacket struct {
	VersionInfo                 []byte               // version information of communications
	ProtocolId                  uint64               // protocol id used in communications
	ConnectTokenExpireTimestamp uint64               // when the connect token expires
	ConnectTokenSequence        uint64               // the sequence id of this token
	Token                       *ConnectTokenPrivate // reference to the private parts of this packet
	ConnectTokenData            []byte               // the encrypted Token after Write -> Encrypt
}

The connection request packet

func (*RequestPacket) GetType

func (p *RequestPacket) GetType() PacketType

func (*RequestPacket) Read

func (p *RequestPacket) Read(packetData []byte, packetLen int, protocolId, currentTimestamp uint64, readPacketKey, privateKey, allowedPackets []byte, replayProtection *ReplayProtection) error

Reads a request packet and decrypts the connect token private data. Request packets do not return a sequenceId

func (*RequestPacket) Sequence

func (p *RequestPacket) Sequence() uint64

request packets do not have a sequence value

func (*RequestPacket) Write

func (p *RequestPacket) Write(buf []byte, protocolId, sequence uint64, writePacketKey []byte) (int, error)

Writes the RequestPacket data to a supplied buffer and returns the length of bytes written to it.

type ResponsePacket

type ResponsePacket struct {
	ChallengeTokenSequence uint64
	ChallengeTokenData     []byte
	// contains filtered or unexported fields
}

Response packet, containing the token data and sequence id

func (*ResponsePacket) GetType

func (p *ResponsePacket) GetType() PacketType

func (*ResponsePacket) Read

func (p *ResponsePacket) Read(packetData []byte, packetLen int, protocolId, currentTimestamp uint64, readPacketKey, privateKey, allowedPackets []byte, replayProtection *ReplayProtection) error

func (*ResponsePacket) Sequence

func (p *ResponsePacket) Sequence() uint64

func (*ResponsePacket) Write

func (p *ResponsePacket) Write(buf []byte, protocolId, sequence uint64, writePacketKey []byte) (int, error)

type Server

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

func NewServer

func NewServer(serverAddress *net.UDPAddr, privateKey []byte, protocolId uint64, maxClients int) *Server

func (*Server) DisconnectClient

func (s *Server) DisconnectClient(clientId uint64, sendDisconnect bool) error

Disconnects a single client via the specified clientId

func (*Server) GetClientIndexByClientId

func (s *Server) GetClientIndexByClientId(clientId uint64) (int, error)

func (*Server) GetClientUserData

func (s *Server) GetClientUserData(clientId uint64) ([]byte, error)

func (*Server) GetConnectedClientIds

func (s *Server) GetConnectedClientIds() []uint64

func (*Server) HasClients

func (s *Server) HasClients() int

func (*Server) Init

func (s *Server) Init() error

func (*Server) Listen

func (s *Server) Listen() error

func (*Server) MaxClients

func (s *Server) MaxClients() int

func (*Server) OnPacketData

func (s *Server) OnPacketData(packetData []byte, addr *net.UDPAddr)

func (*Server) RecvPayload

func (s *Server) RecvPayload(clientIndex int) ([]byte, uint64)

func (*Server) SendPayloadToClient

func (s *Server) SendPayloadToClient(clientId uint64, payloadData []byte) error

Sends the payload to the client specified by their clientId.

func (*Server) SendPayloads

func (s *Server) SendPayloads(payloadData []byte)

func (*Server) SetAllowedPackets

func (s *Server) SetAllowedPackets(allowedPackets []byte)

func (*Server) SetIgnoreRequests

func (s *Server) SetIgnoreRequests(val bool)

func (*Server) SetIgnoreResponses

func (s *Server) SetIgnoreResponses(val bool)

func (*Server) SetTimeout

func (s *Server) SetTimeout(duration time.Duration)

func (*Server) Stop

func (s *Server) Stop() error

func (*Server) Update

func (s *Server) Update(time float64) error

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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