mysql

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: May 10, 2023 License: Apache-2.0, ISC Imports: 12 Imported by: 0

Documentation

Overview

Package mysql is a very basic MySQL connection library. Usage:

  var sql *mysql.Connection := mysql.NewConnection(&mysql.Config{
  Host: targetHost,
  Port: targetPort,
})
err := sql.Connect()
defer sql.Disconnect()

The Connection exports the connection details via the ConnectionLog.

Index

Constants

View Source
const (
	// STATE_NOT_CONNECTED is the start state.
	STATE_NOT_CONNECTED = "NOT_CONNECTED"

	// STATE_CONNECTED is the state after the TCP connection is completed.
	STATE_CONNECTED = "CONNECTED"

	// STATE_SSL_REQUEST is the state after reading a HandshakePacket with
	// SSL capabilities, before sending the SSLRequest packet.
	STATE_SSL_REQUEST = "SSL_REQUEST"

	// STATE_SSL_HANDSHAKE is the state after sending an SSLRequest
	// packet, before peforming an SSL handshake.
	STATE_SSL_HANDSHAKE = "SSL_HANDSHAKE"

	// STATE_FINISHED is the state after the connection has been
	// negotiated (from either CONNECTED or SSL_HANDSHAKE).
	STATE_FINISHED = "STATE_FINISHED"
)
View Source
const (
	CLIENT_LONG_PASSWORD uint32 = (1 << iota)
	CLIENT_FOUND_ROWS
	CLIENT_LONG_FLAG
	CLIENT_CONNECT_WITH_DB
	CLIENT_NO_SCHEMA
	CLIENT_COMPRESS
	CLIENT_ODBC
	CLIENT_LOCAL_FILES
	CLIENT_IGNORE_SPACE
	CLIENT_PROTOCOL_41
	CLIENT_INTERACTIVE
	CLIENT_SSL
	CLIENT_IGNORE_SIGPIPE
	CLIENT_TRANSACTIONS
	CLIENT_RESERVED
	CLIENT_SECURE_CONNECTION
	CLIENT_MULTI_STATEMENTS
	CLIENT_MULTI_RESULTS
	CLIENT_PS_MULTI_RESULTS
	CLIENT_PLUGIN_AUTH
	CLIENT_CONNECT_ATTRS
	CLIENT_PLUGIN_AUTH_LEN_ENC_CLIENT_DATA
	CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS
	CLIENT_SESSION_TRACK
	CLIENT_DEPRECATED_EOF
)

Capability flags: See https://dev.mysql.com/doc/dev/mysql-server/8.0.1/group__group__cs__capabilities__flags.html

View Source
const (
	DEFAULT_TIMEOUT_SECS        = 3
	DEFAULT_PORT                = 3306
	DEFAULT_CLIENT_CAPABILITIES = CLIENT_SSL
	DEFAULT_RESERVED_DATA_HEX   = "0000000000000000000000000000000000000000000000"
)

Config defaults

Variables

View Source
var ErrorCodes = map[uint16]string{}/* 4533 elements not displayed */

ErrorCodes maps the 16-bit error codes to the "ErrorID"s defined in the docs.

Functions

func GetClientCapabilityFlags

func GetClientCapabilityFlags(flags uint32) map[string]bool

GetClientCapabilityFlags returns a map[string]bool representation of the given flags. The keys are the constant names defined in the MySQL docs, and the values are true (flags that are not set have no corresponding map entry).

func GetServerStatusFlags

func GetServerStatusFlags(flags uint16) map[string]bool

GetServerStatusFlags returns a map[string]bool representation of the given flags. The keys are the constant names defined in the MySQL docs, and the values are true (flags that are not set have no corresponding map entry).

Types

type Config

type Config struct {
	ClientCapabilities uint32
	MaxPacketSize      uint32
	CharSet            byte
	ReservedData       []byte
}

Config specifies the client settings for the connection.

func InitConfig

func InitConfig(base *Config) *Config

InitConfig fills in a (possibly newly-created) Config instance with the default values where values are not present.

type Connection

type Connection struct {
	// Config is the client configuration for this connection.
	Config *Config

	// ConnectionState tracks how far along along the client is in
	// negotiating the connection.
	State ConnectionState

	// Connection is the TCP or TLS-wrapped Connection (IsSecure() will
	// tell which)
	Connection net.Conn

	// SequenceNumber is used to number packets to / from the server.
	SequenceNumber uint8

	// ConnectionLog is a log of MySQL packets received/sent.
	ConnectionLog ConnectionLog
}

Connection holds the state of a single connection.

func NewConnection

func NewConnection(config *Config) *Connection

NewConnection creates a new connection object with the given config (using defaults where none is specified).

func (*Connection) Connect

func (c *Connection) Connect(conn net.Conn) error

Connect to the configured server and perform the initial handshake

func (*Connection) Disconnect

func (c *Connection) Disconnect() error

Disconnect from the server and close any underlying connections.

func (*Connection) GetHandshake

func (c *Connection) GetHandshake() *HandshakePacket

GetHandshake attempts to get the Handshake packet from the ConnectionLog; if none is present, returns nil.

func (*Connection) NegotiateTLS

func (c *Connection) NegotiateTLS() error

NegotiateTLS sends the SSL_REQUEST packet (the client should begin the TLS handshake immediately after this returns successfully).

func (*Connection) SupportsTLS

func (c *Connection) SupportsTLS() bool

SupportsTLS checks if both the input client flags and the server capability flags support TLS.

type ConnectionLog

type ConnectionLog struct {
	Handshake  *ConnectionLogEntry `json:"handshake,omitempty"`
	Error      *ConnectionLogEntry `json:"error,omitempty"`
	SSLRequest *ConnectionLogEntry `json:"ssl_request,omitempty"`
}

ConnectionLog is a log of packets sent/received during the connection.

type ConnectionLogEntry

type ConnectionLogEntry struct {
	// Length is the actual length of the packet body.
	Length uint32 `zgrab:"debug" json:"length"`

	// SequenceNumber is the sequence number included in the packet.
	SequenceNumber uint8 `zgrab:"debug" json:"sequence_number"`

	// Raw is the raw packet body, base64-encoded. May be nil on a read
	// error.
	Raw string `zgrab:"debug" json:"raw"`

	// Parsed is the parsed packet body. May be nil on a decode error.
	Parsed PacketInfo `json:"parsed,omitempty"`
}

ConnectionLogEntry is an entry in the ConnectionLog.Entry in the ConnectionLog.

type ConnectionState

type ConnectionState string

ConnectionState tracks the state of the Connection instance.

type ERRPacket

type ERRPacket struct {
	// Header identifies the packet as an ERR_Packet; its value is 0xFF.
	Header byte `zgrab:"debug" json:"header"`

	// ErrorCode identifies the error.
	ErrorCode uint16 `json:"error_code"`

	// SQLStateMarker is a numeric marker of the SQL state.
	SQLStateMarker string `zgrab:"debug" json:"sql_state_marker,omitempty"`

	// SQLStateString is a five-character string representation of the SQL state.
	SQLState string `zgrab:"debug" json:"sql_state,omitempty"`

	// ErrorMessage is a human-readable error message.
	ErrorMessage string `json:"error_message,omitempty"`
}

ERRPacket is returned by the server when there is an error. It is defined at https://web.archive.org/web/20160316124241/https://dev.mysql.com/doc/internals/en/packet-ERRPacket.html

func (*ERRPacket) Error

func (e *ERRPacket) Error() string

Error implements the error interface. Return the code and message.

func (*ERRPacket) GetErrorID

func (e *ERRPacket) GetErrorID() string

GetErrorID returns the error ID associated with this packet's error code.

func (*ERRPacket) GetScanError

func (e *ERRPacket) GetScanError() *zgrab2.ScanError

Get the ScanError for this packet (wrap the error + application error status)

type HandshakePacket

type HandshakePacket struct {
	// ProtocolVersion is the version of the protocol being used.
	ProtocolVersion byte `json:"protocol_version"`

	// ServerVersion is a human-readable server version.
	ServerVersion string `json:"server_version,omitempty"`

	// ConnectionID is the ID used by the server to identify this client.
	ConnectionID uint32 `zgrab:"debug" json:"connection_id,omitempty"`

	// AuthPluginData1 is the first part of the auth-plugin-specific data.
	AuthPluginData1 []byte `zgrab:"debug" json:"auth_plugin_data_part_1,omitempty"`

	// Filler1 is an unused byte, defined to be 0.
	Filler1 byte `zgrab:"debug" json:"filler_1,omitempty"`

	// CharacterSet is the low 8 bits of the default server character-set
	CharacterSet byte `zgrab:"debug" json:"character_set,omitempty"`

	// ShortHandshake is a synthetic field: if true, none of the following
	// fields are present.
	ShortHandshake bool `zgrab:"debug" json:"short_handshake"`

	// StatusFlags is a bit field giving the server's status.
	StatusFlags uint16 `json:"status_flags,omitempty"`

	// CapabilityFlags the combined capability flags, which tell what
	// the server can do (e.g. whether it supports SSL).
	CapabilityFlags uint32 `json:"capability_flags,omitempty"`

	// AuthPluginDataLen is the length of the full auth-plugin-specific
	// data (so len(AuthPluginData1) + len(AuthPluginData2) =
	// AuthPluginDataLen)
	AuthPluginDataLen byte `zgrab:"debug" json:"auth_plugin_data_len,omitempty"`

	// Reserved is defined to be ten bytes of 0x00s.
	Reserved []byte `zgrab:"debug" json:"reserved,omitempty"`

	// AuthPluginData2 is the remainder of the auth-plugin-specific data.
	// Its length is MAX(13, auth_plugin_data_len - 8).
	AuthPluginData2 []byte `zgrab:"debug" json:"auth_plugin_data_part_2,omitempty"`

	// AuthPluginName is the name of the auth plugin. This determines the
	// format / interpretation of AuthPluginData.
	AuthPluginName string `zgrab:"debug" json:"auth_plugin_name,omitempty"`
}

HandshakePacket is the packet the server sends immediately upon a client connecting (unless there is an error, like there are no users allowed to connect from the client's host). The packet format is defined at https://web.archive.org/web/20160316105725/https://dev.mysql.com/doc/internals/en/connection-phase-packets.html This is compatible with at least protocol version 10. Protocol version 9 was 3.22 and prior (1998?).

func (*HandshakePacket) MarshalJSON

func (p *HandshakePacket) MarshalJSON() ([]byte, error)

MarshalJSON omits reserved from encoded packet if it is the default value (ten bytes of 0s).

type OKPacket

type OKPacket struct {
	// Header identifies the packet as an OK_Packet. Either 0x01 or 0xFE.
	Header byte `zgrab:"debug" json:"header"`

	// AffectedRows gives the number of rows affected by the command.
	AffectedRows uint64 `zgrab:"debug" json:"affected_rows"`

	// LastInsertId gives the ID of the last-inserted row.
	LastInsertId uint64 `json:"last_insert_id"`

	// StatusFlags give the server's status (see e.g. https://dev.mysql.com/doc/internals/en/status-flags.html)
	StatusFlags uint16 `json:"status_flags,omitempty"`

	// Warnings is only present if the ClientCapabilities returned by the
	// server contain the flag CLIENT_PROTOCOL_41.
	// Warnings gives the number of warnings.
	Warnings uint16 `json:"warnings,omitempty"`

	// Info gives human readable status information.
	Info string `json:"info,omitempty"`

	// SessionStateChanges is only present if the server has the
	// CLIENT_SESSION_TRACK ClientCapability and the StatusFlags contain
	// SERVER_SESSION_STATE_CHANGED.
	// SessionStateChanges gives state information on the session.
	SessionStateChanges string `zgrab:"debug" json:"session_state_changes,omitempty"`
}

OKPacket is sent by the server in response to a successful command. See e.g. https://dev.mysql.com/doc/internals/en/packet-OK_Packet.html

func (*OKPacket) MarshalJSON

func (p *OKPacket) MarshalJSON() ([]byte, error)

MarshalJSON convert the StatusFlags to an set of consts.

type PacketInfo

type PacketInfo interface {
}

PacketInfo is the top-level interface for all packets.

type SSLRequestPacket

type SSLRequestPacket struct {
	// CapabilityFlags is a bit field of flags that the client supports.
	// CLIENT_SSL (0x0800) must always be set.
	CapabilityFlags uint32 `json:"capability_flags"`

	// MaxPacketSize specifies the maximum size packets the client expects
	// to receive.
	MaxPacketSize uint32 `zgrab:"debug" json:"max_packet_size"`

	// CharacterSet specifies the client's expected character set.
	CharacterSet byte `zgrab:"debug" json:"character_set"`

	// Reserved is a 23-byte string of null characters.
	Reserved []byte `zgrab:"debug" json:"reserved,omitempty"`
}

SSLRequestPacket is the packet sent by the client to inform the server that a TLS handshake follows. It is defined at type defined at https://web.archive.org/web/20160316105725/https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest

func (*SSLRequestPacket) EncodeBody

func (p *SSLRequestPacket) EncodeBody() []byte

EncodeBody encodes the SSLRequestPacket for transport to the server.

func (*SSLRequestPacket) MarshalJSON

func (p *SSLRequestPacket) MarshalJSON() ([]byte, error)

MarshalJSON omits reserved from encoded packet if it is the default value (ten bytes of 0s).

type WritablePacket

type WritablePacket interface {
	PacketInfo
	EncodeBody() []byte
}

WritablePacket is a sub-interface for those packets that must be sent by the client to the server, and not just read.

Jump to

Keyboard shortcuts

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