proxy

package
v0.45.0 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2024 License: Apache-2.0 Imports: 71 Imported by: 38

Documentation

Overview

Package proxy contains Gate's Minecraft Java edition proxy implementation.

Index

Constants

View Source
const (
	DownstreamServerResourcePackOrigin = resourcepack.DownstreamServerOrigin
	PluginOnProxyResourcePackOrigin    = resourcepack.PluginOnProxyOrigin
)
View Source
const (
	// ChatMessageType is a standard chat message and
	// lets the chat message appear in the client's HUD.
	// These messages can be filtered out by the client's settings.
	ChatMessageType = chat.ChatMessageType
	// SystemMessageType is a system chat message.
	// e.g. client is willing to accept messages from commands,
	// but does not want general chat from other players.
	// It lets the chat message appear in the client's HUD and can't be dismissed.
	SystemMessageType = chat.SystemMessageType
	// GameInfoMessageType lets the chat message appear above the player's main HUD.
	// This text format doesn't support many component features, such as hover events.
	GameInfoMessageType = chat.GameInfoMessageType
)

Chat message types.

Variables

View Source
var (
	ErrNoBackendConnection = errors.New("player has no backend server connection yet")
	ErrTooLongChatMessage  = errors.New("server bound chat message can not exceed 256 characters")
)
View Source
var ErrProxyAlreadyRun = errors.New("proxy was already run, create a new one")

ErrProxyAlreadyRun is returned by Proxy.Run if the proxy instance was already run.

View Source
var ErrServerAlreadyExists = errors.New("server already exists")

ErrServerAlreadyExists indicates that a server is already registered in ServerRegistrar.

View Source
var ErrServerOnlineMode = errors.New("backend server is online mode, but should be offline")

ErrServerOnlineMode indicates error in a ConnectionRequest when the backend server is in online mode.

View Source
var ErrTransferUnsupportedClientProtocol = errors.New("player version must be 1.20.5 to be able to transfer to another host")
View Source
var Plugins []Plugin

Plugins is used to register plugins with the proxy. The plugin's init hook is run after the proxy is initialized and before serving any connections.

If one init hook errors, the proxy cancels the boot and shuts down; will fire the ShutdownEvent so other plugins can gracefully de-initialize.

Functions

func BroadcastMessage added in v0.19.1

func BroadcastMessage(sinks []MessageSink, msg component.Component)

BroadcastMessage broadcasts a message to all given sinks (e.g. Player).

func BroadcastPluginMessage added in v0.19.1

func BroadcastPluginMessage(sinks []message.ChannelMessageSink, identifier message.ChannelIdentifier, data []byte)

BroadcastPluginMessage sends the plugin message to all players on the server.

func PlayersToSlice added in v0.19.1

func PlayersToSlice[R any](p Players) []R

PlayersToSlice returns a slice of all players.

func RegisteredServerEqual added in v0.17.0

func RegisteredServerEqual(a, b RegisteredServer) bool

RegisteredServerEqual returns true if RegisteredServer a and b are equal. They are never equal if one of them is nil.

func ServerInfoEqual added in v0.17.0

func ServerInfoEqual(a, b ServerInfo) bool

ServerInfoEqual returns true if ServerInfo a and b are equal. They are never equal if one of them is nil.

func WithMessageSender added in v0.19.0

func WithMessageSender(id uuid.UUID) command.MessageOption

WithMessageSender modifies the sender identity of the chat message.

func WithMessageType added in v0.19.0

func WithMessageType(t MessageType) command.MessageOption

WithMessageType modifies chat message type.

Types

type ChatState added in v0.39.0

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

ChatState tracks the last Secure Chat state that we received from the client. This is important to always have a valid 'last seen' state that is consistent with future and past updates from the client (which may be signed). This state is used to construct 'spoofed' command packets from the proxy to the server.

  • If we last forwarded a chat or command packet from the client, we have a known 'last seen' that we can reuse.
  • If we last forwarded a ChatAcknowledgementPacket, the previous 'last seen' cannot be reused. We cannot predict an up-to-date 'last seen', as we do not know which messages the client actually saw.
  • Therefore, we need to hold back any acknowledgement packets so that we can continue to reuse the last valid 'last seen' state.
  • However, there is a limit to the number of messages that can remain unacknowledged on the server.
  • To address this, we know that if the client has moved its 'last seen' window far enough, we can fill in the gap with dummy 'last seen', and it will never be checked.

Note that this is effectively unused for 1.20.5+ clients, as commands without any signature do not send 'last seen' updates.

func (*ChatState) AccumulateAckCount added in v0.39.0

func (cs *ChatState) AccumulateAckCount(ackCount int) int

func (*ChatState) CreateLastSeen added in v0.39.0

func (cs *ChatState) CreateLastSeen() chat.LastSeenMessages

func (*ChatState) LastTimestamp added in v0.39.0

func (cs *ChatState) LastTimestamp() time.Time

func (*ChatState) UpdateFromMessage added in v0.39.0

func (cs *ChatState) UpdateFromMessage(timestamp *time.Time, lastSeenMessages *chat.LastSeenMessages) *chat.LastSeenMessages

type CommandExecuteEvent

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

CommandExecuteEvent is fired when someone wants to execute a command.

func (*CommandExecuteEvent) Allowed

func (c *CommandExecuteEvent) Allowed() bool

Allowed returns true when the command is allowed to be executed.

func (*CommandExecuteEvent) Command

func (c *CommandExecuteEvent) Command() string

Command returns the whole commandline without the leading "/".

func (*CommandExecuteEvent) Forward added in v0.12.0

func (c *CommandExecuteEvent) Forward() bool

Forward returns true when the command should be forwarded to the server.

func (*CommandExecuteEvent) OriginalCommand added in v0.12.0

func (c *CommandExecuteEvent) OriginalCommand() string

OriginalCommand returns the original command if SetCommand has changed it.

func (*CommandExecuteEvent) SetAllowed

func (c *CommandExecuteEvent) SetAllowed(allowed bool)

SetAllowed sets whether the command is allowed to be executed.

func (*CommandExecuteEvent) SetCommand added in v0.12.0

func (c *CommandExecuteEvent) SetCommand(commandline string)

SetCommand changes the command being executed without the leading "/".

func (*CommandExecuteEvent) SetForward added in v0.12.0

func (c *CommandExecuteEvent) SetForward(forward bool)

SetForward sets whether the command should be forwarded to the server.

func (*CommandExecuteEvent) Source

func (c *CommandExecuteEvent) Source() command.Source

Source returns the command source that wants to run the command.

type ConnectionEvent added in v0.26.3

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

ConnectionEvent is fired when a client connects with the proxy. It can be used for low-level connection handling, modifying or closing the connection. This event is fired before ConnectionHandshakeEvent

func (*ConnectionEvent) Connection added in v0.26.3

func (e *ConnectionEvent) Connection() net.Conn

Connection returns the connection.

func (*ConnectionEvent) OriginalConnection added in v0.26.3

func (e *ConnectionEvent) OriginalConnection() ConnectionEventConn

OriginalConnection returns the original connection.

func (*ConnectionEvent) SetConnection added in v0.26.3

func (e *ConnectionEvent) SetConnection(conn net.Conn)

SetConnection sets new connection to use for this connection.

type ConnectionEventConn added in v0.26.3

type ConnectionEventConn interface {
	net.Conn
	Closed() bool // Whether Close was called.
}

ConnectionEventConn tracks whether Close was called on the connection.

type ConnectionHandshakeEvent

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

ConnectionHandshakeEvent is fired when a handshake is established between a client and the proxy.

func (*ConnectionHandshakeEvent) Connection

func (e *ConnectionHandshakeEvent) Connection() Inbound

Connection returns the inbound connection.

func (*ConnectionHandshakeEvent) Intent added in v0.37.0

Intent returns the handshake intent.

type ConnectionRequest

type ConnectionRequest interface {
	// Server returns the server that this connection request is for.
	Server() RegisteredServer
	// Connect blocks, initiates the connection to the
	// remote Server and returns a result after the user has logged on
	// or an error when an error occurred (e.g. could not net.Dial the Server, ctx was canceled, etc.).
	//
	// The given Context can be used to cancel the connection initiation, but
	// has no effect if the connection was already established or canceled.
	//
	// No messages will be communicated to the client:
	// You are responsible for all error handling.
	Connect(ctx context.Context) (ConnectionResult, error)
	// ConnectWithIndication is the same as Connect, but the proxy's built-in
	// handling will be used to provide errors to the player and returns
	// true if the player was successfully connected.
	ConnectWithIndication(ctx context.Context) (successful bool)
}

ConnectionRequest can send a connection request to another server on the proxy. A connection request is created using Player.CreateConnectionRequest(RegisteredServer).

type ConnectionResult

type ConnectionResult interface {
	Status() ConnectionStatus // The connection result status.
	// Reason returns a reason for the failure to connect to the server.
	// It is nil if not provided.
	Reason() Component
}

ConnectionResult is the result of a ConnectionRequest.

type ConnectionStatus

type ConnectionStatus uint8

ConnectionStatus is the status for a ConnectionResult

const (
	// SuccessConnectionStatus indicates that the player was successfully connected to the server.
	SuccessConnectionStatus ConnectionStatus = iota
	// AlreadyConnectedConnectionStatus indicates that the player is already connected to this server.
	AlreadyConnectedConnectionStatus
	// InProgressConnectionStatus indicates that a connection is already in progress.
	InProgressConnectionStatus
	// CanceledConnectionStatus indicates that a plugin has cancelled this connection.
	CanceledConnectionStatus
	// ServerDisconnectedConnectionStatus indicates that the server disconnected the player.
	// A reason MAY be provided in the ConnectionResult.Reason().
	ServerDisconnectedConnectionStatus
)

func (ConnectionStatus) AlreadyConnected

func (r ConnectionStatus) AlreadyConnected() bool

AlreadyConnected id true if the player is already connected to this server.

func (ConnectionStatus) Canceled

func (r ConnectionStatus) Canceled() bool

Canceled is true if a plugin has cancelled this connection.

func (ConnectionStatus) ConnectionInProgress

func (r ConnectionStatus) ConnectionInProgress() bool

ConnectionInProgress is true if a connection is already in progress.

func (ConnectionStatus) ServerDisconnected

func (r ConnectionStatus) ServerDisconnected() bool

ServerDisconnected is true if the server disconnected the player. A reason MAY be provided in the ConnectionResult.Reason().

func (ConnectionStatus) Successful

func (r ConnectionStatus) Successful() bool

Successful is true if the player was successfully connected to the server.

type DisconnectEvent

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

func (*DisconnectEvent) LoginStatus

func (e *DisconnectEvent) LoginStatus() LoginStatus

func (*DisconnectEvent) Player

func (e *DisconnectEvent) Player() Player

type DisconnectPlayerKickResult

type DisconnectPlayerKickResult struct {
	Reason component.Component
}

DisconnectPlayerKickResult is a ServerKickResult and tells the proxy to disconnect the player with the specified reason.

type GameProfileProvider added in v0.17.0

type GameProfileProvider interface {
	GameProfile() (profile *profile.GameProfile)
}

GameProfileProvider provides the GameProfile for a player connection.

type GameProfileRequestEvent

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

GameProfileRequestEvent is fired after the PreLoginEvent in order to set up the game profile for the user. This can be used to configure a custom profile for a user, i.e. skin replacement.

func NewGameProfileRequestEvent

func NewGameProfileRequestEvent(
	inbound Inbound,
	original profile.GameProfile,
	onlineMode bool,
) *GameProfileRequestEvent

NewGameProfileRequestEvent creates a new GameProfileRequestEvent.

func (*GameProfileRequestEvent) Conn

func (e *GameProfileRequestEvent) Conn() Inbound

Conn returns the inbound connection that is connecting to the proxy.

func (*GameProfileRequestEvent) GameProfile

func (e *GameProfileRequestEvent) GameProfile() profile.GameProfile

GameProfile returns the game profile that will be used to initialize the connection with. Should no profile be set, the original profile (given by the proxy) will be used.

func (*GameProfileRequestEvent) OnlineMode

func (e *GameProfileRequestEvent) OnlineMode() bool

OnlineMode specifies whether the user connected in online/offline mode.

func (*GameProfileRequestEvent) Original

Original returns the by the proxy created offline or online (Mojang authenticated) game profile.

func (*GameProfileRequestEvent) SetGameProfile

func (e *GameProfileRequestEvent) SetGameProfile(p profile.GameProfile)

SetGameProfile sets the profile to use for this connection.

type HandshakeAddresser added in v0.17.0

type HandshakeAddresser interface {
	HandshakeAddr(defaultPlayerVirtualHost string, player Player) (newPlayerVirtualHost string)
}

HandshakeAddresser provides the ServerAddress sent with the packet.Handshake when a player joins the server implementing this interface. A ServerInfo of a registered server or a RegisteredServer can implement this interface. If no ServerInfo or RegisteredServer implements this interface the ServerInfo.Addr the default ServerAddress is used or the BungeeCord forwarding scheme if the proxy is in cfg.LegacyForwardingMode.

type Inbound

type Inbound interface {
	Protocol() proto.Protocol // The current protocol version the connection uses.
	VirtualHost() net.Addr    // The hostname, the client sent us, to join the server, if applicable.
	RemoteAddr() net.Addr     // The player's IP address.
	Active() bool             // Whether the connection remains active.
	// Context returns the connection's context that can be used to know when the connection was closed.
	// (e.g. for canceling work in an event handler)
	Context() context.Context
}

Inbound is an incoming connection to the proxy.

type KickedFromServerEvent

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

Fired when a player is kicked from a server. You may either allow the proxy to kick the player (with an optional reason override) or redirect the player to a separate server. By default, the proxy will notify the user (if they are already connected to a server) or disconnect them (if they are not on a server and no other servers are available).

func (*KickedFromServerEvent) KickedDuringServerConnect

func (e *KickedFromServerEvent) KickedDuringServerConnect() bool

KickedDuringServerConnect returns true if the player got kicked while connecting to another server.

func (*KickedFromServerEvent) OriginalReason

func (e *KickedFromServerEvent) OriginalReason() component.Component

OriginalReason returns the reason the server kicked the player from the server. May return nil!

func (*KickedFromServerEvent) Player

func (e *KickedFromServerEvent) Player() Player

Player returns the player that got kicked.

func (*KickedFromServerEvent) Result

Result returns current kick result. The proxy sets a default non-nil result but an event handler may has set it nil when handling the event.

func (*KickedFromServerEvent) Server

Server returns the server the player got kicked from.

func (*KickedFromServerEvent) SetResult

func (e *KickedFromServerEvent) SetResult(result ServerKickResult)

SetResult sets the kick result.

type LoginEvent

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

func (*LoginEvent) Allow

func (e *LoginEvent) Allow()

func (*LoginEvent) Allowed

func (e *LoginEvent) Allowed() bool

func (*LoginEvent) Deny

func (e *LoginEvent) Deny(reason component.Component)

func (*LoginEvent) Player

func (e *LoginEvent) Player() Player

func (*LoginEvent) Reason

func (e *LoginEvent) Reason() component.Component

Is nil if Allowed() returns true

type LoginPhaseConnection added in v0.19.0

type LoginPhaseConnection interface {
	Inbound
	crypto.KeyIdentifiable
	SendLoginPluginMessage(identifier message.ChannelIdentifier, contents []byte, consumer MessageConsumer) error
}

LoginPhaseConnection allows the server to communicate with a client logging into the proxy using login plugin messages.

type LoginStatus

type LoginStatus uint8
const (
	SuccessfulLoginStatus LoginStatus = iota
	ConflictingLoginStatus
	CanceledByUserLoginStatus
	CanceledByProxyLoginStatus
	CanceledByUserBeforeCompleteLoginStatus
)

type MessageConsumer added in v0.19.0

type MessageConsumer interface {
	OnMessageResponse(responseBody []byte) error // responseBody may be empty
}

type MessageSink added in v0.19.1

type MessageSink interface {
	// SendMessage sends a message component to the entity.
	SendMessage(msg component.Component, opts ...command.MessageOption) error
}

MessageSink is a message sink.

type MessageType added in v0.13.0

type MessageType = chat.MessageType

MessageType is a chat message type.

type NotifyKickResult

type NotifyKickResult struct {
	Message component.Component
}

NotifyKickResult is ServerKickResult and notifies the player with the specified message but does nothing else. This is only a valid result to use if the player was trying to connect to a different server, otherwise it is treated like a DisconnectPlayerKickResult result.

type Options

type Options struct {
	// Config requires configuration
	// validated by cfg.Validate.
	Config *config.Config
	// The event manager to use.
	// If none is set, no events are sent.
	EventMgr event.Manager
	// Authenticator to authenticate users in online mode.
	// If not set, creates a default one.
	Authenticator auth.Authenticator
}

Options are the options for a new Java edition Proxy.

type PermissionsSetupEvent

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

PermissionsSetupEvent is fired once a permission.Subject's permissions are being initialized.

func (*PermissionsSetupEvent) Func

Func returns the permission.Func used for the subject.

func (*PermissionsSetupEvent) SetFunc

func (p *PermissionsSetupEvent) SetFunc(fn permission.Func)

SetFunc sets the permission.Func usec for the subject. If fn is nil, the default Func fill be used.

func (*PermissionsSetupEvent) Subject

Subject returns the subject the permissions are setup for.

type PingEvent

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

PingEvent is fired when a request for server information is sent by a remote client, or when the server sends the MOTD and favicon to the client after a successful login. The proxy will wait on this event to finish firing before delivering the results to the remote client, but you are urged to handle this event as quickly as possible when handling this event due to the amount of ping packets a client can send.

func (*PingEvent) Connection

func (p *PingEvent) Connection() Inbound

Connection returns the inbound connection.

func (*PingEvent) Ping

func (p *PingEvent) Ping() *ping.ServerPing

Ping returns the used ping. (pre-initialized by the proxy)

func (*PingEvent) SetPing

func (p *PingEvent) SetPing(ping *ping.ServerPing)

SetPing sets the ping response to use.

type Player

type Player interface {
	Inbound
	netmc.PacketWriter
	command.Source
	message.ChannelMessageSource
	// ChannelMessageSink sends a plugin message to the player's client.
	//
	// Note that this method does not send a plugin message to the server the player
	// is connected to. You should only use this method if you are trying to communicate
	// with a mod that is installed on the player's client.
	// To send a plugin message to the server from the player,
	// you should use CurrentServer(), check for non-nil and then currSrv.SendPluginMessage().
	message.ChannelMessageSink
	crypto.KeyIdentifiable

	ID() uuid.UUID    // The Minecraft ID of the player.
	Username() string // The username of the player.
	// CurrentServer returns the current server connection of the player.
	CurrentServer() ServerConnection // May be nil, if there is no backend server connection!
	Ping() time.Duration             // The player's ping or -1 if currently unknown.
	OnlineMode() bool                // Whether the player was authenticated with Mojang's session servers.
	// CreateConnectionRequest creates a connection request to begin switching the backend server.
	CreateConnectionRequest(target RegisteredServer) ConnectionRequest
	GameProfile() profile.GameProfile // Returns the player's game profile.
	Settings() player.Settings        // The player's client settings. Returns player.DefaultSettings if unknown.
	// Disconnect disconnects the player with a reason.
	// Once called, further interface calls to this player become undefined.
	Disconnect(reason component.Component)
	// SpoofChatInput sends chats input onto the player's current server as if
	// they typed it into the client chat box.
	SpoofChatInput(input string) error
	// SendResourcePack sends the specified resource pack from url to the user.
	// If at all possible, specify an 20-byte SHA-1 hash of the resource pack file.
	// To monitor the status of the sent resource pack, subscribe to PlayerResourcePackStatusEvent.
	SendResourcePack(info ResourcePackInfo) error
	// AppliedResourcePacks returns all applied resource packs that were applied to the player.
	AppliedResourcePacks() []*ResourcePackInfo
	// PendingResourcePacks returns all pending resource packs that are currently being sent to the player.
	PendingResourcePacks() []*ResourcePackInfo
	// SendActionBar sends an action bar to the player.
	SendActionBar(msg component.Component) error
	// TabList returns the player's tab list.
	// Used for modifying the player's tab list and header/footer.
	TabList() tablist.TabList
	ClientBrand() string // Returns the player's client brand. Empty if unspecified.
	// TransferToHost transfers the player to the specified host.
	// The host should be in the format of "host:port" or just "host" in which case the port defaults to 25565.
	// If the player is from a version lower than 1.20.5, this method will return ErrTransferUnsupportedClientProtocol.
	TransferToHost(addr string) error

	// AppliedResourcePack returns the resource pack that was applied to the player.
	// Returns nil if no resource pack was applied.
	//
	// Deprecated: Use AppliedResourcePacks instead.
	AppliedResourcePack() *ResourcePackInfo
	// PendingResourcePack returns the resource pack that is currently being sent to the player.
	// Returns nil if no resource pack is being sent.
	//
	// Deprecated: Use PendingResourcePacks instead.
	PendingResourcePack() *ResourcePackInfo
}

Player is a connected Minecraft player.

type PlayerAvailableCommandsEvent added in v0.12.0

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

PlayerAvailableCommandsEvent allows plugins to modify the packet indicating commands available on the server to a Minecraft 1.13+ client.

func (*PlayerAvailableCommandsEvent) Player added in v0.12.0

Player returns the player that is about to see the available commands.

func (*PlayerAvailableCommandsEvent) RootNode added in v0.12.0

RootNode returns the available commands to the Player.

type PlayerChannelRegisterEvent added in v0.19.0

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

PlayerChannelRegisterEvent is fired when a client Player sends a plugin message through the register channel. The proxy will not wait on this event to finish firing.

func (*PlayerChannelRegisterEvent) Channels added in v0.19.0

func (*PlayerChannelRegisterEvent) Player added in v0.19.0

func (e *PlayerChannelRegisterEvent) Player() Player

type PlayerChatEvent

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

PlayerChatEvent is fired when a player sends a chat message. Note that messages with a leading "/" do not trigger this event, but instead CommandExecuteEvent.

func (*PlayerChatEvent) Allowed

func (c *PlayerChatEvent) Allowed() bool

Allowed returns true when the chat message is allowed.

func (*PlayerChatEvent) Message

func (c *PlayerChatEvent) Message() string

Message returns the message that will be sent by the player.

func (*PlayerChatEvent) Original added in v0.19.0

func (c *PlayerChatEvent) Original() string

Original returns the original message the player sent.

func (*PlayerChatEvent) Player

func (c *PlayerChatEvent) Player() Player

Player returns the player that sent the message.

func (*PlayerChatEvent) SetAllowed

func (c *PlayerChatEvent) SetAllowed(allowed bool)

SetAllowed sets whether the chat message is allowed. Deprecated: for 1.19.1 and newer, set this as denied will kick users.

func (*PlayerChatEvent) SetMessage added in v0.19.0

func (c *PlayerChatEvent) SetMessage(msg string)

SetMessage modifies the message of the player.

type PlayerChooseInitialServerEvent

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

PlayerChooseInitialServerEvent is fired when a player has finished the login process, and we need to choose the first server to connect to. The proxy will wait on this event to finish firing before initiating the connection but you should try to limit the work done in this event. Failures will be handled by KickedFromServerEvent as normal.

func (*PlayerChooseInitialServerEvent) InitialServer

InitialServer returns the initial server or nil if no server is configured.

func (*PlayerChooseInitialServerEvent) Player

Player returns the player to find the initial server for.

func (*PlayerChooseInitialServerEvent) SetInitialServer

func (e *PlayerChooseInitialServerEvent) SetInitialServer(server RegisteredServer)

SetInitialServer sets the initial server for the player.

type PlayerClientBrandEvent added in v0.35.0

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

PlayerClientBrandEvent is fired when a Player sends the `minecraft:brand` plugin message. The proxy will not wait on event handlers to finish firing.

func (*PlayerClientBrandEvent) Brand added in v0.35.0

func (e *PlayerClientBrandEvent) Brand() string

func (*PlayerClientBrandEvent) Player added in v0.35.0

func (e *PlayerClientBrandEvent) Player() Player

type PlayerModInfoEvent

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

PlayerModInfoEvent is fired when a Forge client sends its mods to the proxy while connecting to a server.

func (*PlayerModInfoEvent) ModInfo

func (e *PlayerModInfoEvent) ModInfo() modinfo.ModInfo

ModInfo is the mod info received by the player.

func (*PlayerModInfoEvent) Player

func (e *PlayerModInfoEvent) Player() Player

Player returns the player who sent the mod info.

type PlayerResourcePackStatusEvent added in v0.19.0

type PlayerResourcePackStatusEvent = resourcepack.PlayerResourcePackStatusEvent

PlayerResourcePackStatusEvent is fired when the status of a resource pack sent to the player by the server is changed. Depending on the result of this event (which the proxy will wait until completely fired), the player may be kicked from the server.

type PlayerSettingsChangedEvent

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

func (*PlayerSettingsChangedEvent) Player

func (s *PlayerSettingsChangedEvent) Player() Player

Player returns the player whose settings where updates/initialized.

func (*PlayerSettingsChangedEvent) Settings

Settings returns player's new settings.

type Players

type Players interface {
	Len() int                  // Returns the size of the player list.
	Range(func(p Player) bool) // Loops through the players, breaks if func returns false.
}

Players is a list of players safe for concurrent use.

type Plugin

type Plugin struct {
	Name string // The name identifying the plugin.
	// The hook to initialize the plugin.
	// The proxy is passed to the plugin, so it can register event listeners, commands and so on.
	// The init function should not block the proxy from starting.
	//
	// The context is canceled when the proxy is shutting down.
	// The plugin can use the proxy's logger available via logr.FromContextOrDiscard(ctx) or logr.FromContext(ctx)
	// and should name it after the plugin's name with logger.WithName.
	Init func(ctx context.Context, proxy *Proxy) error
}

Plugin provides the ability to extend Gate with external code.

Quick notes on Go's plugin system:

We don't support Go's plugin system as it is not a mature solution. They force your plugin implementation to be highly-coupled with Gate's build toolchain, the end-result would be very brittle, hard to maintain and the overhead would be much higher if the plugin author does not have any control over new versions of Gate.

Now with that made clear, here is how Gate can be customized!

Native Go:

You can use Gate as a framework and compile your code with it.

  • Create your own Go project/module and `go get -u go.minekube.com/gate`
  • Within your main function
  • Add your Plugin to the Plugins
  • And call cmd/gate.Execute (blocking your main until shutdown).
  • Subscribe to proxy.ShutdownEvent for de-initializing your plugin in a blocking manner.

By running cmd/gate.Execute, Gate will do the whole rest.

  • load the cfg (parse found file, flags and env vars)
  • make and run the proxy.Proxy that will call the Plugins init hooks.

Script languages:

  • Not yet supported.

type PluginMessageEvent

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

PluginMessageEvent is fired when a plugin message is sent to the proxy, either from a player or a server backend server.

func (*PluginMessageEvent) Allowed

func (p *PluginMessageEvent) Allowed() bool

func (*PluginMessageEvent) Data

func (p *PluginMessageEvent) Data() []byte

func (*PluginMessageEvent) Identifier

func (*PluginMessageEvent) SetForward

func (p *PluginMessageEvent) SetForward(forward bool)

func (*PluginMessageEvent) Source

func (*PluginMessageEvent) Target

type PostLoginEvent

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

func (*PostLoginEvent) Player

func (e *PostLoginEvent) Player() Player

type PreLoginEvent

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

PreLoginEvent is fired when a player has initiated a connection with the proxy but before the proxy authenticates the player with Mojang or before the player's proxy connection is fully established (for offline mode).

func (*PreLoginEvent) Allow

func (e *PreLoginEvent) Allow()

func (*PreLoginEvent) Conn

func (e *PreLoginEvent) Conn() Inbound

Conn returns the inbound connection that is connecting to the proxy.

func (*PreLoginEvent) Deny

func (e *PreLoginEvent) Deny(reason component.Component)

func (*PreLoginEvent) ForceOfflineMode

func (e *PreLoginEvent) ForceOfflineMode()

func (*PreLoginEvent) ForceOnlineMode

func (e *PreLoginEvent) ForceOnlineMode()

func (*PreLoginEvent) ID added in v0.37.0

func (e *PreLoginEvent) ID() (uuid.UUID, bool)

ID returns the UUID of the connecting player. May be uuid.Nil! This value is nil on 1.19.2 and lower, up to 1.20.1 it is optional and from 1.20.2 it will always be available.

func (*PreLoginEvent) Reason

func (e *PreLoginEvent) Reason() component.Component

Reason returns the `deny reason` to disconnect the connection. May be nil!

func (*PreLoginEvent) Result

func (e *PreLoginEvent) Result() PreLoginResult

Result returns the current result of the PreLoginEvent.

func (*PreLoginEvent) Username

func (e *PreLoginEvent) Username() string

Username returns the username of the player.

type PreLoginResult

type PreLoginResult uint8

PreLoginResult is the result of a PreLoginEvent.

const (
	AllowedPreLogin PreLoginResult = iota
	DeniedPreLogin
	ForceOnlineModePreLogin
	ForceOfflineModePreLogin
)

PreLoginResult values.

type PreShutdownEvent

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

PreShutdownEvent is fired before the proxy begins to shut down by stopping to accept new connections and disconnect all players.

func (*PreShutdownEvent) Reason

func (s *PreShutdownEvent) Reason() component.Component

Reason returns the shutdown reason used to disconnect players with. May be nil!

func (*PreShutdownEvent) SetReason

func (s *PreShutdownEvent) SetReason(reason component.Component)

SetReason sets the shutdown reason used to disconnect players with.

type PreTransferEvent added in v0.37.0

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

PreTransferEvent is fired before a player is transferred to another host, either by the backend server or by a plugin using the Player.TransferTo method.

func (*PreTransferEvent) Addr added in v0.37.0

func (e *PreTransferEvent) Addr() net.Addr

Addr returns the target address the player will be transferred to.

func (*PreTransferEvent) Allowed added in v0.37.0

func (e *PreTransferEvent) Allowed() bool

Allowed returns true if the transfer is allowed.

func (*PreTransferEvent) Player added in v0.37.0

func (e *PreTransferEvent) Player() Player

Player returns the player that is about to be transferred.

func (*PreTransferEvent) TransferTo added in v0.37.0

func (e *PreTransferEvent) TransferTo(addr net.Addr)

TransferTo changes the target address the player will be transferred to.

type Proxy

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

Proxy is Gate's Java edition Minecraft proxy.

func New

func New(options Options) (p *Proxy, err error)

New returns a new Proxy ready to start.

func (*Proxy) ChannelRegistrar

func (p *Proxy) ChannelRegistrar() *message.ChannelRegistrar

func (*Proxy) Command

func (p *Proxy) Command() *command.Manager

Command returns the Proxy's command manager.

func (*Proxy) Config

func (p *Proxy) Config() config.Config

Config returns the cfg used by the Proxy.

func (*Proxy) DisconnectAll

func (p *Proxy) DisconnectAll(reason component.Component)

DisconnectAll disconnects all current connected players in parallel and waits until all players have been disconnected.

func (*Proxy) Event

func (p *Proxy) Event() event.Manager

Event returns the Proxy's event manager.

func (*Proxy) HandleConn added in v0.17.0

func (p *Proxy) HandleConn(raw net.Conn)

HandleConn handles a just-accepted client connection that has not had any I/O performed on it yet.

func (*Proxy) Player

func (p *Proxy) Player(id uuid.UUID) Player

Player returns the online player by their Minecraft id. Returns nil if the player was not found.

func (*Proxy) PlayerByName

func (p *Proxy) PlayerByName(username string) Player

PlayerByName returns the online player by their Minecraft name (search is case-insensitive). Returns nil if the player was not found.

func (*Proxy) PlayerCount

func (p *Proxy) PlayerCount() int

PlayerCount returns the number of players on the proxy.

func (*Proxy) Players

func (p *Proxy) Players() []Player

Players returns all players on the proxy.

func (*Proxy) Register

func (p *Proxy) Register(info ServerInfo) (RegisteredServer, error)

Register - See ServerRegistrar

func (*Proxy) Server

func (p *Proxy) Server(name string) RegisteredServer

Server gets a backend server registered with the proxy by name. Returns nil if not found.

func (*Proxy) Servers

func (p *Proxy) Servers() []RegisteredServer

Servers gets all registered servers.

func (*Proxy) Shutdown

func (p *Proxy) Shutdown(reason component.Component)

Shutdown stops the Proxy and/or blocks until the Proxy has finished shutdown.

It first stops listening for new connections, disconnects all existing connections with the given reason (nil = blank reason) and waits for all event subscribers to finish.

func (*Proxy) Start

func (p *Proxy) Start(ctx context.Context) error

Start runs the Java edition Proxy, blocks until the proxy is Shutdown or an error occurred while starting. The Proxy is already shutdown on method return. Another method of stopping the Proxy is to call Shutdown. A Proxy can only be run once or ErrProxyAlreadyRun is returned.

func (*Proxy) Unregister

func (p *Proxy) Unregister(info ServerInfo) bool

Unregister unregisters the server exactly matching the given ServerInfo and returns true if found.

type ReadyEvent

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

ReadyEvent is fired once the proxy was successfully initialized and is ready to serve connections.

May be triggered multiple times on config reloads.

func (*ReadyEvent) Addr added in v0.33.0

func (r *ReadyEvent) Addr() string

Addr returns the address the proxy is listening on.

type RedirectPlayerKickResult

type RedirectPlayerKickResult struct {
	Server  RegisteredServer    // The new server to redirect the kicked player to.
	Message component.Component // Optional message sent to the player after redirecting.
}

RedirectPlayerKickResult is a ServerKickResult and tells the proxy to redirect the player to another server.

type RegisteredServer

type RegisteredServer interface {
	ServerInfo() ServerInfo
	Players() Players // The players connected to the server on THIS proxy.
}

RegisteredServer is a backend server that has been registered with the proxy.

type ResourcePackInfo added in v0.19.0

type ResourcePackInfo = resourcepack.Info

ResourcePackInfo is resource-pack options for Player.SendResourcePack.

type ResourcePackOrigin added in v0.19.0

type ResourcePackOrigin = resourcepack.Origin

ResourcePackOrigin represents the origin of the resource-pack.

type ResourcePackResponseStatus added in v0.19.0

type ResourcePackResponseStatus = resourcepack.ResponseStatus

ResourcePackResponseStatus represents the possible statuses for the resource pack.

const (
	// SuccessfulResourcePackResponseStatus indicates the resource pack was applied successfully.
	SuccessfulResourcePackResponseStatus ResourcePackResponseStatus = resourcepack.SuccessfulResponseStatus
	// DeclinedResourcePackResponseStatus indicates the player declined to download the resource pack.
	DeclinedResourcePackResponseStatus ResourcePackResponseStatus = resourcepack.DeclinedResponseStatus
	// FailedDownloadResourcePackResponseStatus indicates the player could not download the resource pack.
	FailedDownloadResourcePackResponseStatus ResourcePackResponseStatus = resourcepack.FailedDownloadResponseStatus
	// AcceptedResourcePackResponseStatus indicates the player has accepted the resource pack and is now downloading it.
	AcceptedResourcePackResponseStatus ResourcePackResponseStatus = resourcepack.AcceptedResponseStatus
	// DownloadedResourcePackResponseStatus indicates the player has downloaded the resource pack.
	DownloadedResourcePackResponseStatus ResourcePackResponseStatus = resourcepack.DownloadedResponseStatus
	// InvalidURLResourcePackResponseStatus indicates the URL of the resource pack failed to load.
	InvalidURLResourcePackResponseStatus ResourcePackResponseStatus = resourcepack.InvalidURLResponseStatus
	// FailedToReloadResourcePackResponseStatus indicates the player failed to reload the resource pack.
	FailedToReloadResourcePackResponseStatus ResourcePackResponseStatus = resourcepack.FailedToReloadResponseStatus
	// DiscardedResourcePackResponseStatus indicates the resource pack was discarded.
	DiscardedResourcePackResponseStatus ResourcePackResponseStatus = resourcepack.DiscardedResponseStatus
)

type ServerConnectedEvent

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

ServerConnectedEvent is fired before the player completely transitions to the target server and the connection to the previous server has been de-established.

Use Server to get the target server since Player.CurrentServer is yet nil or listen for ServerPostConnectEvent instead.

func (*ServerConnectedEvent) EntityID added in v0.25.0

func (s *ServerConnectedEvent) EntityID() int

EntityID returns the current entity ID of the player. This is the entity ID the player has on the connected server and changes every time the player connects to a new server.

func (*ServerConnectedEvent) Player

func (s *ServerConnectedEvent) Player() Player

Player returns the associated player.

func (*ServerConnectedEvent) PreviousServer

func (s *ServerConnectedEvent) PreviousServer() RegisteredServer

PreviousServer returns the server the player was previously connected to. May return nil if there was none!

func (*ServerConnectedEvent) Server

Server returns the server the player connected to.

type ServerConnection

type ServerConnection interface {
	message.ChannelMessageSink
	message.ChannelMessageSource

	Server() RegisteredServer // Returns the server that this connection is connected to.
	Player() Player           // Returns the player that this connection is associated with.
}

ServerConnection is a connection to a backend server from the proxy for a client.

type ServerDialer added in v0.17.0

type ServerDialer interface {
	Dial(ctx context.Context, player Player) (net.Conn, error)
}

ServerDialer provides the server connection for a joining player. A ServerInfo of a registered server or a RegisteredServer can implement this interface to provide custom connection establishment when a player wants to join a server. If no ServerInfo or RegisteredServer implements this interface the ServerInfo.Addr is used to dial the server using tcp.

type ServerInfo

type ServerInfo interface {
	Name() string   // Returns the server name.
	Addr() net.Addr // Returns the server address.
}

ServerInfo is the info of a backend server.

func NewServerInfo

func NewServerInfo(name string, addr net.Addr) ServerInfo

type ServerKickResult

type ServerKickResult interface {
	// contains filtered or unexported methods
}

ServerKickResult is the result of a KickedFromServerEvent and is implemented by

DisconnectPlayerKickResult

RedirectPlayerKickResult

NotifyKickResult

type ServerLoginPluginMessageEvent added in v0.19.0

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

ServerLoginPluginMessageEvent is fired when a server sends a login plugin message to the proxy. Plugins have the opportunity to respond to the messages as needed. The proxy will wait on this event to finish. The server will be responsible for continuing the login process once the server is satisfied with any login plugin responses sent by proxy plugins (or messages indicating a lack of response).

func (*ServerLoginPluginMessageEvent) Contents added in v0.19.0

func (e *ServerLoginPluginMessageEvent) Contents() []byte

Contents returns the contents of the login plugin message sent by the server.

func (*ServerLoginPluginMessageEvent) Result added in v0.19.0

func (*ServerLoginPluginMessageEvent) SequenceID added in v0.19.0

func (e *ServerLoginPluginMessageEvent) SequenceID() int

SequenceID returns the sequence id of the login plugin message sent by the server.

type ServerLoginPluginMessageResult added in v0.19.0

type ServerLoginPluginMessageResult struct {
	Response []byte
}

func (*ServerLoginPluginMessageResult) Allowed added in v0.19.0

func (r *ServerLoginPluginMessageResult) Allowed() bool

func (*ServerLoginPluginMessageResult) Copy added in v0.19.0

func (*ServerLoginPluginMessageResult) Reply added in v0.19.0

type ServerPostConnectEvent

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

ServerPostConnectEvent is fired after the player has connected to a server. The server the player is now connected to is available in Player().CurrentServer().

func (*ServerPostConnectEvent) Player

func (s *ServerPostConnectEvent) Player() Player

Player returns the associated player.

func (*ServerPostConnectEvent) PreviousServer

func (s *ServerPostConnectEvent) PreviousServer() RegisteredServer

PreviousServer returns the server the player was previously connected to. May return nil if there was none!

type ServerPreConnectEvent

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

ServerPreConnectEvent is fired before the player connects to a server.

func (*ServerPreConnectEvent) Allow

func (e *ServerPreConnectEvent) Allow(server RegisteredServer)

Allow the player to connect to the specified server.

func (*ServerPreConnectEvent) Allowed

func (e *ServerPreConnectEvent) Allowed() bool

Allowed returns true whether the connection is allowed.

func (*ServerPreConnectEvent) Deny

func (e *ServerPreConnectEvent) Deny()

Deny will cancel the player to connect to another server.

func (*ServerPreConnectEvent) OriginalServer

func (e *ServerPreConnectEvent) OriginalServer() RegisteredServer

OriginalServer returns the server that the player originally tried to connect to. To get the server the player will connect to, see the Server() of this event. To get the server the player is currently on when this event is fired, use Player.getCurrentServer().

func (*ServerPreConnectEvent) Player

func (e *ServerPreConnectEvent) Player() Player

Player returns the player that tries to connect to another server.

func (*ServerPreConnectEvent) Server

Server returns the server the player will connect to OR nil if Allowed() returns false.

type ServerRegistrar added in v0.17.0

type ServerRegistrar interface {
	// Register registers a server with the proxy and returns it.
	// If the there is already a server with the same info
	// error ErrServerAlreadyExists is returned and the already registered server.
	Register(info ServerInfo) (RegisteredServer, error)
	// Unregister unregisters the server exactly matching the
	// given ServerInfo and returns true if found.
	Unregister(info ServerInfo) bool
}

ServerRegistrar is used to register servers.

type ServerRegistry added in v0.17.0

type ServerRegistry interface {
	// Server gets a registered server by name or returns nil if not found.
	Server(name string) RegisteredServer
	ServerRegistrar
}

ServerRegistry is used to retrieve registered servers that players can connect to.

type ServerResourcePackSendEvent added in v0.19.0

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

ServerResourcePackSendEvent is fired when the downstream server tries to send a player a ResourcePack packet. The proxy will wait on this event to finish before forwarding the resource pack to the user. If this event is denied, it will retroactively send a DENIED status to the downstream server in response. If the downstream server has it set to "forced" it will forcefully disconnect the user.

func (*ServerResourcePackSendEvent) Allowed added in v0.19.0

func (e *ServerResourcePackSendEvent) Allowed() bool

Allowed indicated whether sending the resource pack to the client is allowed.

func (*ServerResourcePackSendEvent) ProvidedResourcePack added in v0.19.0

func (e *ServerResourcePackSendEvent) ProvidedResourcePack() ResourcePackInfo

ProvidedResourcePack returns the resource pack provided to the client if allowed.

func (*ServerResourcePackSendEvent) ReceivedResourcePack added in v0.19.0

func (e *ServerResourcePackSendEvent) ReceivedResourcePack() ResourcePackInfo

ReceivedResourcePack returns the resource pack send by the server.

func (*ServerResourcePackSendEvent) ServerConnection added in v0.19.0

func (e *ServerResourcePackSendEvent) ServerConnection() ServerConnection

ServerConnection returns the associated server connection.

func (*ServerResourcePackSendEvent) SetAllowed added in v0.19.0

func (e *ServerResourcePackSendEvent) SetAllowed(allowed bool)

SetAllowed allows or denies sending the resource pack to the client.

func (*ServerResourcePackSendEvent) SetProvidedResourcePack added in v0.19.0

func (e *ServerResourcePackSendEvent) SetProvidedResourcePack(pack ResourcePackInfo)

SetProvidedResourcePack sets the resource pack provided to the client if allowed.

type ShutdownEvent

type ShutdownEvent struct{}

ShutdownEvent is fired by the proxy after the proxy has stopped accepting connections and PreShutdownEvent, but before the proxy process exits.

Subscribe to this event to gracefully stop any subtasks, such as plugin dependencies.

type TabCompleteEvent added in v0.12.0

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

TabCompleteEvent is fired after a tab complete response is sent by the remote server, for clients on1.12.2 and below. You have the opportunity to modify the response sent to the remote player.

func (*TabCompleteEvent) PartialMessage added in v0.12.0

func (t *TabCompleteEvent) PartialMessage() string

PartialMessage returns the message being partially completed.

func (*TabCompleteEvent) Player added in v0.12.0

func (t *TabCompleteEvent) Player() Player

Player returns the player requesting the tab completion.

func (*TabCompleteEvent) SetSuggestions added in v0.12.0

func (t *TabCompleteEvent) SetSuggestions(s []string)

SetSuggestions sets the suggestions provided to the user.

func (*TabCompleteEvent) Suggestions added in v0.12.0

func (t *TabCompleteEvent) Suggestions() []string

Suggestions returns all the suggestions provided to the user, as a mutable list.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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