minecraft

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: May 21, 2020 License: MIT Imports: 28 Imported by: 110

Documentation

Overview

Package minecraft implements Minecraft Bedrock Edition connections. It implements a Dial() function to dial a connection to a Minecraft server and a Listen() function to create a listener in order to listen for incoming Minecraft connections. Typically these connections are done over RakNet, which is implemented by the github.com/sandertv/go-raknet package.

The minecraft package provides a high level abstraction over Minecraft network related features. It handles the authentication, encryption and spawning sequence by itself and users can send and read packets implemented in the minecraft/protocol/packet package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Conn

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

Conn represents a Minecraft (Bedrock Edition) connection over a specific net.Conn transport layer. Its methods (Read, Write etc.) are safe to be called from multiple goroutines simultaneously.

func Dial

func Dial(network string, address string) (conn *Conn, err error)

Dial dials a Minecraft connection to the address passed over the network passed. The network is typically "raknet". A Conn is returned which may be used to receive packets from and send packets to.

A zero value of a Dialer struct is used to initiate the connection. A custom Dialer may be used to specify additional behaviour.

func (*Conn) ChunkRadius

func (conn *Conn) ChunkRadius() int

ChunkRadius returns the initial chunk radius of the connection. For connections obtained through a Listener, this is the radius that the client requested. For connections obtained through a Dialer, this is the radius that the server approved upon.

func (*Conn) ClientCacheEnabled

func (conn *Conn) ClientCacheEnabled() bool

ClientCacheEnabled checks if the connection has the client blob cache enabled. If true, the server may send blobs to the client to reduce network transmission, but if false, the client does not support it, and the server must send chunks as usual.

func (*Conn) ClientData

func (conn *Conn) ClientData() login.ClientData

ClientData returns the client data the client connected with. Note that this client data may be changed during the session, so the data should only be used directly after connection, and should be updated after that by the caller.

func (*Conn) Close

func (conn *Conn) Close() error

Close closes the Conn and its underlying connection. Before closing, it also calls Flush() so that any packets currently pending are sent out.

func (*Conn) DoSpawn

func (conn *Conn) DoSpawn() error

DoSpawn starts the game for the client in the server. DoSpawn should be called for a Conn obtained using minecraft.Dial(). Use Conn.StartGame to spawn a Conn obtained using a minecraft.Listener. DoSpawn will start the spawning sequence using the game data found in conn.GameData(), which was sent earlier by the server.

func (*Conn) Flush

func (conn *Conn) Flush() error

Flush flushes the packets currently buffered by the connections to the underlying net.Conn, so that they are directly sent.

func (*Conn) GameData

func (conn *Conn) GameData() GameData

GameData returns specific game data set to the connection for the player to be initialised with. If the Conn is obtained using Listen, this game data may be set to the Listener. If obtained using Dial, the data is obtained from the server.

func (*Conn) IdentityData

func (conn *Conn) IdentityData() login.IdentityData

IdentityData returns the identity data of the connection. It holds the UUID, XUID and username of the connected client.

func (*Conn) LocalAddr

func (conn *Conn) LocalAddr() net.Addr

LocalAddr returns the local address of the underlying connection.

func (*Conn) Read

func (conn *Conn) Read(b []byte) (n int, err error)

Read reads a packet from the connection into the byte slice passed, provided the byte slice is big enough to carry the full packet. It is recommended to use ReadPacket() rather than Read() in cases where reading is done directly.

func (*Conn) ReadPacket

func (conn *Conn) ReadPacket() (pk packet.Packet, err error)

ReadPacket reads a packet from the Conn, depending on the packet ID that is found in front of the packet data. If a read deadline is set, an error is returned if the deadline is reached before any packet is received. The packet received must not be held until the next packet is read using ReadPacket(). If the same type of packet is read, the previous one will be invalidated.

If the packet read was not implemented, a *packet.Unknown is returned, containing the raw payload of the packet read.

func (*Conn) RemoteAddr

func (conn *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote address of the underlying connection.

func (*Conn) ResourcePacks

func (conn *Conn) ResourcePacks() []*resource.Pack

ResourcePacks returns a slice of all resource packs the connection holds. For a Conn obtained using a Listener, this holds all resource packs set to the Listener. For a Conn obtained using Dial, the resource packs include all packs sent by the server connected to.

func (*Conn) SetDeadline

func (conn *Conn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadline of the connection. It is equivalent to calling SetReadDeadline and SetWriteDeadline at the same time.

func (*Conn) SetReadDeadline

func (conn *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline of the Conn to the time passed. The time must be after time.Now(). Passing an empty time.Time to the method (time.Time{}) results in the read deadline being cleared.

func (*Conn) SetWriteDeadline

func (conn *Conn) SetWriteDeadline(time.Time) error

SetWriteDeadline is a stub function to implement net.Conn. It has no functionality.

func (*Conn) StartGame

func (conn *Conn) StartGame(data GameData) error

StartGame starts the game for a client that connected to the server. StartGame should be called for a Conn obtained using a minecraft.Listener. The game data passed will be used to spawn the player in the world of the server. To spawn a Conn obtained from a call to minecraft.Dial(), use Conn.DoSpawn().

func (*Conn) Write

func (conn *Conn) Write(b []byte) (n int, err error)

Write writes a slice of serialised packet data to the Conn. The data is buffered until the next 20th of a tick, after which it is flushed to the connection. Write returns the amount of bytes written n.

func (*Conn) WritePacket

func (conn *Conn) WritePacket(pk packet.Packet) error

WritePacket encodes the packet passed and writes it to the Conn. The encoded data is buffered until the next 20th of a second, after which the data is flushed and sent over the connection.

type Dialer

type Dialer struct {
	// ErrorLog is a log.Logger that errors that occur during packet handling of servers are written to. By
	// default, ErrorLog is set to one equal to the global logger.
	ErrorLog *log.Logger

	// ClientData is the client data used to login to the server with. It includes fields such as the skin,
	// locale and UUIDs unique to the client. If empty, a default is sent produced using defaultClientData().
	ClientData login.ClientData
	// IdentityData is the identity data used to login to the server with. It includes the username, UUID and
	// XUID of the player.
	// The IdentityData object is obtained using Minecraft auth if Email and Password are set. If not, the
	// object provided here is used, or a default one if left empty.
	IdentityData login.IdentityData

	// Email is the email used to login to the XBOX Live account. If empty, no attempt will be made to login,
	// and an unauthenticated login request will be sent.
	Email string
	// Password is the password used to login to the XBOX Live account. If Email is non-empty, a login attempt
	// will be made using this password.
	Password string

	// PacketFunc is called whenever a packet is read from or written to the connection returned when using
	// Dialer.Dial(). It includes packets that are otherwise covered in the connection sequence, such as the
	// Login packet. The function is called with the header of the packet and its raw payload, the address
	// from which the packet originated, and the destination address.
	PacketFunc func(header packet.Header, payload []byte, src, dst net.Addr)

	// EnableClientCache, if set to true, enables the client blob cache for the client. This means that the
	// server will send chunks as blobs, which may be saved by the client so that chunks don't have to be
	// transmitted every time, resulting in less network transmission.
	EnableClientCache bool
}

Dialer allows specifying specific settings for connection to a Minecraft server. The zero value of Dialer is used for the package level Dial function.

func (Dialer) Dial

func (dialer Dialer) Dial(network string, address string) (conn *Conn, err error)

Dial dials a Minecraft connection to the address passed over the network passed. The network is typically "raknet". A Conn is returned which may be used to receive packets from and send packets to. Specific fields in the Dialer specify additional behaviour during the connection, such as authenticating to XBOX Live and custom client data.

type GameData

type GameData struct {
	// WorldName is the name of the world that the player spawns in. This name will be displayed at the top of
	// the player list when opening the in-game menu. It may contain colour codes and does not have to be an
	// actual world name, but instead, can be the server name.
	// If WorldName is left empty, the name of the Listener will be used to show above the player list
	// in-game.
	WorldName string
	// Difficulty is the difficulty of the world that the player spawns in. A difficulty of 0, peaceful, means
	// the player will automatically regenerate health and hunger.
	Difficulty int32
	// EntityUniqueID is the unique ID of the player. The unique ID is unique for the entire world and is
	// often used in packets. Most servers send an EntityUniqueID equal to the EntityRuntimeID.
	EntityUniqueID int64
	// EntityRuntimeID is the runtime ID of the player. The runtime ID is unique for each world session, and
	// entities are generally identified in packets using this runtime ID.
	EntityRuntimeID uint64
	// PlayerGameMode is the game mode the player currently has. It is a value from 0-4, with 0 being
	// survival mode, 1 being creative mode, 2 being adventure mode, 3 being survival spectator and 4 being
	// creative spectator.
	// This field may be set to 5 to make the client fall back to the game mode set in the WorldGameMode
	// field.
	PlayerGameMode int32
	// PlayerPosition is the spawn position of the player in the world. In servers this is often the same as
	// the world's spawn position found below.
	PlayerPosition mgl32.Vec3
	// Pitch is the vertical rotation of the player. Facing straight forward yields a pitch of 0. Pitch is
	// measured in degrees.
	Pitch float32
	// Yaw is the horizontal rotation of the player. Yaw is also measured in degrees.
	Yaw float32
	// Dimension is the ID of the dimension that the player spawns in. It is a value from 0-2, with 0 being
	// the overworld, 1 being the nether and 2 being the end.
	Dimension int32
	// WorldSpawn is the block on which the world spawn of the world. This coordinate has no effect on the
	// place that the client spawns, but it does have an effect on the direction that a compass points.
	WorldSpawn protocol.BlockPos
	// WorldGameMode is the game mode that a player gets when it first spawns in the world. It is shown in the
	// settings and is used if the PlayerGameMode is set to 5.
	WorldGameMode int32
	// GameRules defines game rules currently active with their respective values. The value of these game
	// rules may be either 'bool', 'int32' or 'float32'. Some game rules are server side only, and don't
	// necessarily need to be sent to the client.
	GameRules map[string]interface{}
	// Time is the total time that has elapsed since the start of the world.
	Time int64
	// Blocks is a list of all blocks and variants existing in the game. Failing to send any of the blocks
	// that are in the game, including any specific variants of that block, will crash mobile clients. It
	// seems Windows 10 games do not crash.
	Blocks []interface{}
	// Items is a list of all items existing in the game. Failing to send any of the default items that are in
	// the game will crash mobile clients.
	Items []protocol.ItemEntry
	// ServerAuthoritativeMovement specifies if the client should use the 'server authoritative movement',
	// meaning it will send PlayerAuthInput packets instead of MovePlayer packets, which the server should
	// verify.
	ServerAuthoritativeMovement bool
}

GameData is a loose wrapper around a part of the data found in the StartGame packet. It holds data sent specifically at the start of the game, such as the position of the player, the game mode, etc.

type Listener

type Listener struct {
	// ErrorLog is a log.Logger that errors that occur during packet handling of clients are written to. By
	// default, ErrorLog is set to one equal to the global logger.
	ErrorLog *log.Logger

	// AuthenticationDisables specifies if authentication of players that join is disabled. If set to true, no
	// verification will be done to ensure that the player connecting is authenticated using their XBOX Live
	// account.
	AuthenticationDisabled bool

	// ServerName is the server name shown in the in-game menu, above the player list. The name cannot be
	// changed after a player is connected. By default, 'Minecraft Server' will be set.
	ServerName string
	// MaximumPlayers is the maximum amount of players accepted in the server. If non-zero, players that
	// attempt to join while the server is full will be kicked during login. If zero, the maximum player count
	// will be dynamically updated each time a player joins, so that an unlimited amount of players is
	// accepted into the server.
	MaximumPlayers int
	// ShowVersion specifies if the supported Minecraft version should be shown in the MOTD of the server. If
	// set to false, if set to true, the lowest supported version will be displayed.
	ShowVersion bool

	// ResourcePacks is a slice of resource packs that the listener may hold. Each client will be asked to
	// download these resource packs upon joining.
	ResourcePacks []*resource.Pack
	// TexturePacksRequired specifies if clients that join must accept the texture pack in order for them to
	// be able to join the server. If they don't accept, they can only leave the server.
	TexturePacksRequired bool

	// PacketFunc is called whenever a packet is read from or written to a connection returned when using
	// Listener.Accept. It includes packets that are otherwise covered in the connection sequence, such as the
	// Login packet. The function is called with the header of the packet and its raw payload, the address
	// from which the packet originated, and the destination address.
	PacketFunc func(header packet.Header, payload []byte, src, dst net.Addr)
	// contains filtered or unexported fields
}

Listener implements a Minecraft listener on top of an unspecific net.Listener. It abstracts away the login sequence of connecting clients and provides the implements the net.Listener interface to provide a consistent API.

func Listen

func Listen(network, address string) (*Listener, error)

Listen announces on the local network address. The network must be "tcp", "tcp4", "tcp6", "unix", "unixpacket" or "raknet". A Listener is returned which may be used to accept connections. If the host in the address parameter is empty or a literal unspecified IP address, Listen listens on all available unicast and anycast IP addresses of the local system. Listen has the default values for the fields of Listener filled out. To use different values for these fields, call &Listener{}.Listen() instead.

func (*Listener) Accept

func (listener *Listener) Accept() (net.Conn, error)

Accept accepts a fully connected (on Minecraft layer) connection which is ready to receive and send packets. It is recommended to cast the net.Conn returned to a *minecraft.Conn so that it is possible to use the conn.ReadPacket() and conn.WritePacket() methods. Accept returns an error if the listener is closed.

func (*Listener) Addr

func (listener *Listener) Addr() net.Addr

Addr returns the address of the underlying listener.

func (*Listener) Close

func (listener *Listener) Close() error

Close closes the listener and the underlying net.Listener. Pending calls to Accept will fail immediately.

func (*Listener) Disconnect

func (listener *Listener) Disconnect(conn *Conn, message string) error

Disconnect disconnects a Minecraft Conn passed by first sending a disconnect with the message passed, and closing the connection after. If the message passed is empty, the client will be immediately sent to the player list instead of a disconnect screen.

func (*Listener) HijackPong added in v0.1.0

func (listener *Listener) HijackPong(address string) error

HijackPong hijacks the pong response from a server at an address passed. The listener passed will continuously update its pong data by hijacking the pong data of the server at the address. The hijack will last until the listener is shut down. If the address passed could not be resolved, an error is returned. Calling HijackPong means that any current and future pong data set using listener.PongData is overwritten each update.

func (*Listener) Listen added in v0.12.0

func (listener *Listener) Listen(network, address string) error

Listen announces on the local network address. The network is typically "raknet". If the host in the address parameter is empty or a literal unspecified IP address, Listen listens on all available unicast and anycast IP addresses of the local system.

func (*Listener) StatusProvider added in v1.5.0

func (listener *Listener) StatusProvider(p ServerStatusProvider)

StatusProvider sets a server status provider to dynamically provide the status of the server. StatusProvider will overwrite the status shown in the server list through the MaximumPlayers field and the current connected players.

type ServerStatusProvider

type ServerStatusProvider interface {
	// ServerStatus returns the server status which includes the MOTD/server name, amount of online players
	// and the amount of maximum players.
	ServerStatus() (motd string, onlinePlayers, maxPlayers int)
}

ServerStatusProvider represents a value that is able to provide the status of a server, in specific its MOTD, the amount of online players and the player limit. These providers may be used to display different information in the server list. Although they overwrite the server name, maximum players and online players maintained by a Listener in the server list, these values are not changed and will still be used internally to check if players are able to be connected. Players will still be disconnected if the maximum player count as set in the MaximumPlayers field of a Listener is reached (unless MaximumPlayers is 0).

Directories

Path Synopsis
Package auth implements authentication to Microsoft accounts and XBOX Live accounts.
Package auth implements authentication to Microsoft accounts and XBOX Live accounts.
Package nbt implements the NBT formats used by Minecraft Bedrock Edition and Minecraft Java Edition.
Package nbt implements the NBT formats used by Minecraft Bedrock Edition and Minecraft Java Edition.
Package protocol implements structures and functions used to write or read data related to the Minecraft Bedrock Edition protocol.
Package protocol implements structures and functions used to write or read data related to the Minecraft Bedrock Edition protocol.
packet
Package packet implements every packet in the Minecraft Bedrock Edition protocol using the functions found in the minecraft/protocol package.
Package packet implements every packet in the Minecraft Bedrock Edition protocol using the functions found in the minecraft/protocol package.
Package resource implements the compiling of resource packs found in files, directories or raw byte data.
Package resource implements the compiling of resource packs found in files, directories or raw byte data.

Jump to

Keyboard shortcuts

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