net

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2024 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AuthNativePassword      = "mysql_native_password"
	AuthCachingSha2Password = "caching_sha2_password"
	AuthTiDBSM3Password     = "tidb_sm3_password"
	AuthMySQLClearPassword  = "mysql_clear_password"
	AuthSocket              = "auth_socket"
	AuthTiDBSessionToken    = "tidb_session_token"
	AuthTiDBAuthToken       = "tidb_auth_token"
)
View Source
const (
	ShaCommand   = 1
	FastAuthFail = 4
)
View Source
const (
	AttrNameClientVersion = "_client_version" // libmysqlclient & Connector/C++ & Connector/J & Connector/Net & Connector/Python
	AttrNameClientName1   = "_client_name"    // libmysqlclient & Connector/C++ & Connector/J & Connector/Python & mysqlnd
	AttrNameClientName2   = "_program_name"   // Connector/Net
	AttrNameProgramName   = "program_name"    // MySQL Client & MySQL Shell
)

The connection attribute names that are logged. https://dev.mysql.com/doc/mysql-perfschema-excerpt/8.2/en/performance-schema-connection-attribute-tables.html

View Source
const (
	ServerStatusInTrans            uint16 = 0x0001
	ServerStatusAutocommit         uint16 = 0x0002
	ServerMoreResultsExists        uint16 = 0x0008
	ServerStatusNoGoodIndexUsed    uint16 = 0x0010
	ServerStatusNoIndexUsed        uint16 = 0x0020
	ServerStatusCursorExists       uint16 = 0x0040
	ServerStatusLastRowSend        uint16 = 0x0080
	ServerStatusDBDropped          uint16 = 0x0100
	ServerStatusNoBackslashEscaped uint16 = 0x0200
	ServerStatusMetadataChanged    uint16 = 0x0400
	ServerStatusWasSlow            uint16 = 0x0800
	ServerPSOutParams              uint16 = 0x1000
)

Server information.

View Source
const (
	DefaultConnBufferSize = 32 * 1024
)
View Source
const (
	// MaxPayloadLen is the max packet payload length.
	MaxPayloadLen = 1<<24 - 1
)

Variables

View Source
var (
	ErrReadConn     = errors.New("failed to read the connection")
	ErrWriteConn    = errors.New("failed to write the connection")
	ErrRelayConn    = errors.New("failed to relay the connection")
	ErrFlushConn    = errors.New("failed to flush the connection")
	ErrCloseConn    = errors.New("failed to close the connection")
	ErrHandshakeTLS = errors.New("failed to complete tls handshake")
)
View Source
var (
	ServerVersion = mysql.ServerVersion
	Collation     = uint8(mysql.DefaultCollationID)
	Status        = ServerStatusAutocommit
)
View Source
var (
	ErrInvalidSequence = dbterror.ClassServer.NewStd(errno.ErrInvalidSequence)
)
View Source
var (
	ErrSaltNotLongEnough = errors.New("salt is not long enough")
)

Functions

func Attr2ZapFields

func Attr2ZapFields(attrs map[string]string) []zap.Field

Attr2ZapFields converts connection attributes to log fields. We only pick some of them because others may be too sensitive to be logged.

func DumpLengthEncodedInt

func DumpLengthEncodedInt(buffer []byte, n uint64) []byte

func DumpLengthEncodedString

func DumpLengthEncodedString(buffer []byte, bytes []byte) []byte

DumpLengthEncodedString dumps string<int>.

func DumpUint16

func DumpUint16(buffer []byte, n uint16) []byte

func DumpUint32

func DumpUint32(buffer []byte, n uint32) []byte

func IsDisconnectError

func IsDisconnectError(err error) bool

IsDisconnectError returns whether the error is caused by peer disconnection.

func IsEOFPacket

func IsEOFPacket(firstByte byte, length int) bool

IsEOFPacket returns true if it's an EOF packet.

func IsErrorPacket

func IsErrorPacket(firstByte byte) bool

IsErrorPacket returns true if it's an error packet.

func IsMySQLError added in v0.2.0

func IsMySQLError(err error) bool

IsMySQLError returns true if the error is a MySQL error.

func IsOKPacket

func IsOKPacket(firstByte byte) bool

IsOKPacket returns true if it's an OK packet (but not ResultSet OK).

func IsResultSetOKPacket

func IsResultSetOKPacket(firstByte byte, length int) bool

IsResultSetOKPacket returns true if it's an OK packet after the result set when CLIENT_DEPRECATE_EOF is enabled. A row packet may also begin with 0xfe, so we need to judge it with the packet length. See https://mariadb.com/kb/en/result-set-packets/

func MakeChangeUser

func MakeChangeUser(req *ChangeUserReq, capability Capability) []byte

MakeChangeUser creates the data of COM_CHANGE_USER.

func MakeHandshakeResponse

func MakeHandshakeResponse(resp *HandshakeResp) []byte

func ParseErrorPacket

func ParseErrorPacket(data []byte) *gomysql.MyError

ParseErrorPacket transforms an error packet into a MyError object.

func ParseLengthEncodedBytes

func ParseLengthEncodedBytes(b []byte) ([]byte, bool, int, error)

func ParseLengthEncodedInt

func ParseLengthEncodedInt(b []byte) (num uint64, isNull bool, n int)

func ParseNullTermString

func ParseNullTermString(b []byte) (str []byte, remain []byte)

func ParseOKPacket

func ParseOKPacket(data []byte) uint16

ParseOKPacket parses an OK packet and only returns server status.

func ParseQueryPacket added in v1.0.0

func ParseQueryPacket(data []byte) string

ParseQueryPacket returns the statement in the CMD_QUERY packet. data is the payload after byte CMD_QUERY.

func ReadFull

func ReadFull(prw packetReadWriter, b []byte) error

ReadFull is used to replace io.ReadFull to erase boundary check, function calls and interface conversion. It is a hot path when many rows are returned.

func ReadServerVersion

func ReadServerVersion(conn net.Conn) (string, error)

ReadServerVersion only reads server version.

func SkipLengthEncodedInt

func SkipLengthEncodedInt(b []byte) int

SkipLengthEncodedInt skips the int and only returns the length of the encoded int.

func WithProxy

func WithProxy(pi *PacketIO)

func WithRemoteAddr

func WithRemoteAddr(readdr string, addr net.Addr) func(pi *PacketIO)

func WithWrapError

func WithWrapError(err error) func(pi *PacketIO)

func WriteServerVersion

func WriteServerVersion(conn net.Conn, serverVersion string) error

WriteServerVersion only writes server version. It's only used for testing.

Types

type Capability

type Capability uint32
const (
	ClientLongPassword Capability = 1 << iota
	ClientFoundRows
	ClientLongFlag
	ClientConnectWithDB
	ClientNoSchema
	ClientCompress
	ClientODBC
	ClientLocalFiles
	ClientIgnoreSpace
	ClientProtocol41
	ClientInteractive
	ClientSSL
	ClientIgnoreSigpipe
	ClientTransactions
	ClientReserved
	ClientSecureConnection
	ClientMultiStatements
	ClientMultiResults
	ClientPSMultiResults
	ClientPluginAuth
	ClientConnectAttrs
	ClientPluginAuthLenencClientData
	ClientCanHandleExpiredPasswords
	ClientSessionTrack
	ClientDeprecateEOF
	ClientOptionalResultsetMetadata
	ClientZstdCompressionAlgorithm
	ClientQueryAttributes
	MultiFactorAuthentication
	ClientCapabilityExtension
	ClientSSLVerifyServerCert
	ClientRememberOptions
)

Capability flags. Ref https://dev.mysql.com/doc/dev/mysql-server/latest/group__group__cs__capabilities__flags.html.

func ParseInitialHandshake

func ParseInitialHandshake(data []byte) (Capability, uint64, string)

ParseInitialHandshake parses the initial handshake received from the server.

func (*Capability) MarshalText

func (f *Capability) MarshalText() ([]byte, error)

func (Capability) String

func (f Capability) String() string

func (Capability) Uint32

func (f Capability) Uint32() uint32

func (*Capability) UnmarshalText

func (f *Capability) UnmarshalText(o []byte) error

type ChangeUserReq

type ChangeUserReq struct {
	Attrs      map[string]string
	User       string
	DB         string
	AuthPlugin string
	AuthData   []byte
	Charset    []byte
}

func ParseChangeUser

func ParseChangeUser(data []byte, capability Capability) (*ChangeUserReq, error)

ParseChangeUser parses the data of COM_CHANGE_USER.

type Command

type Command byte
const (
	ComSleep Command = iota
	ComQuit
	ComInitDB
	ComQuery
	ComFieldList
	ComCreateDB
	ComDropDB
	ComRefresh
	ComDeprecated1
	ComStatistics
	ComProcessInfo
	ComConnect
	ComProcessKill
	ComDebug
	ComPing
	ComTime
	ComDelayedInsert
	ComChangeUser
	ComBinlogDump
	ComTableDump
	ComConnectOut
	ComRegisterSlave
	ComStmtPrepare
	ComStmtExecute
	ComStmtSendLongData
	ComStmtClose
	ComStmtReset
	ComSetOption
	ComStmtFetch
	ComDaemon
	ComBinlogDumpGtid
	ComResetConnection
	ComEnd // Not a real command
)

Command information. Ref https://dev.mysql.com/doc/dev/mysql-server/latest/my__command_8h.html#ae2ff1badf13d2b8099af8b47831281e1.

func (Command) Byte

func (f Command) Byte() byte

func (*Command) MarshalText

func (f *Command) MarshalText() ([]byte, error)

func (Command) String

func (f Command) String() string

func (*Command) UnmarshalText

func (f *Command) UnmarshalText(o []byte) error

type CompressAlgorithm

type CompressAlgorithm int

CompressAlgorithm is the algorithm for MySQL compressed protocol.

const (
	// CompressionNone indicates no compression in use.
	CompressionNone CompressAlgorithm = iota
	// CompressionZlib is zlib/deflate.
	CompressionZlib
	// CompressionZstd is Facebook's Zstandard.
	CompressionZstd
)

type HandshakeResp

type HandshakeResp struct {
	Attrs      map[string]string
	User       string
	DB         string
	AuthPlugin string
	AuthData   []byte
	Capability Capability
	ZstdLevel  int
	Collation  uint8
}

HandshakeResp indicates the response read from the client.

func ParseHandshakeResponse

func ParseHandshakeResponse(data []byte) (*HandshakeResp, error)
type Header byte
const (
	OKHeader          Header = 0x00
	ErrHeader         Header = 0xff
	EOFHeader         Header = 0xfe
	AuthSwitchHeader  Header = 0xfe
	LocalInFileHeader Header = 0xfb
)

Header information.

func (Header) Byte

func (f Header) Byte() byte

func (Header) String

func (f Header) String() string

type PacketIO

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

PacketIO is a helper to read and write sql and proxy protocol.

func NewPacketIO

func NewPacketIO(conn net.Conn, lg *zap.Logger, bufferSize int, opts ...PacketIOption) *PacketIO

func (*PacketIO) ApplyOpts

func (p *PacketIO) ApplyOpts(opts ...PacketIOption)

func (*PacketIO) ClientTLSHandshake

func (p *PacketIO) ClientTLSHandshake(tlsConfig *tls.Config) error

func (*PacketIO) Close

func (p *PacketIO) Close() error

func (*PacketIO) EnableProxyClient

func (p *PacketIO) EnableProxyClient(proxy *proxyprotocol.Proxy)

func (*PacketIO) EnableProxyServer

func (p *PacketIO) EnableProxyServer()

func (*PacketIO) Flush

func (p *PacketIO) Flush() error

func (*PacketIO) ForwardUntil

func (p *PacketIO) ForwardUntil(dest *PacketIO, isEnd func(firstByte byte, firstPktLen int) (end, needData bool),
	process func(response []byte) error) error

func (*PacketIO) GetSequence

func (p *PacketIO) GetSequence() uint8

GetSequence is used in tests to assert that the sequences on the client and server are equal.

func (*PacketIO) GracefulClose

func (p *PacketIO) GracefulClose() error

func (*PacketIO) InBytes

func (p *PacketIO) InBytes() uint64

func (*PacketIO) InPackets added in v1.0.0

func (p *PacketIO) InPackets() uint64

func (*PacketIO) IsPeerActive

func (p *PacketIO) IsPeerActive() bool

func (*PacketIO) LastKeepAlive

func (p *PacketIO) LastKeepAlive() config.KeepAlive

LastKeepAlive is used for test.

func (*PacketIO) LocalAddr

func (p *PacketIO) LocalAddr() net.Addr

func (*PacketIO) OutBytes

func (p *PacketIO) OutBytes() uint64

func (*PacketIO) OutPackets added in v1.0.0

func (p *PacketIO) OutPackets() uint64

func (*PacketIO) Proxy

func (p *PacketIO) Proxy() *proxyprotocol.Proxy

Proxy returned parsed proxy header from clients if any.

func (*PacketIO) ReadPacket

func (p *PacketIO) ReadPacket() (data []byte, err error)

ReadPacket reads data and removes the header

func (*PacketIO) ReadSSLRequestOrHandshakeResp

func (p *PacketIO) ReadSSLRequestOrHandshakeResp() (pkt []byte, isSSL bool, err error)

func (*PacketIO) RemoteAddr

func (p *PacketIO) RemoteAddr() net.Addr

func (*PacketIO) ResetSequence

func (p *PacketIO) ResetSequence()

func (*PacketIO) ServerTLSHandshake

func (p *PacketIO) ServerTLSHandshake(tlsConfig *tls.Config) (tls.ConnectionState, error)

func (*PacketIO) SetCompressionAlgorithm

func (p *PacketIO) SetCompressionAlgorithm(algorithm CompressAlgorithm, zstdLevel int) error

func (*PacketIO) SetKeepalive

func (p *PacketIO) SetKeepalive(cfg config.KeepAlive) error

func (*PacketIO) TLSConnectionState

func (p *PacketIO) TLSConnectionState() tls.ConnectionState

func (*PacketIO) WriteEOFPacket

func (p *PacketIO) WriteEOFPacket(status uint16) error

WriteEOFPacket writes an EOF packet. It's only for testing.

func (*PacketIO) WriteErrPacket

func (p *PacketIO) WriteErrPacket(merr *mysql.MyError) error

WriteErrPacket writes an Error packet.

func (*PacketIO) WriteInitialHandshake

func (p *PacketIO) WriteInitialHandshake(capability Capability, salt [20]byte, authPlugin string, serverVersion string, connID uint64) error

WriteInitialHandshake writes an initial handshake as a server. It's used for tenant-aware routing and testing.

func (*PacketIO) WriteOKPacket

func (p *PacketIO) WriteOKPacket(status uint16, header Header) error

WriteOKPacket writes an OK packet. It's only for testing.

func (*PacketIO) WritePacket

func (p *PacketIO) WritePacket(data []byte, flush bool) (err error)

WritePacket writes data without a header

func (*PacketIO) WriteShaCommand

func (p *PacketIO) WriteShaCommand() error

func (*PacketIO) WriteSwitchRequest

func (p *PacketIO) WriteSwitchRequest(authPlugin string, salt [20]byte) error

WriteSwitchRequest writes a switch request to the client. It's only for testing.

func (*PacketIO) WriteUserError

func (p *PacketIO) WriteUserError(err error)

WriteUserError writes an unknown error to the client.

type PacketIOption

type PacketIOption = func(*PacketIO)

Jump to

Keyboard shortcuts

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