net

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2024 License: Apache-2.0 Imports: 31 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"
	AuthLDAPSimple          = "authentication_ldap_simple"
	AuthLDAPSASL            = "authentication_ldap_sasl"
)
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)
)

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 BinaryDate added in v1.3.0

func BinaryDate(pos int, paramValues []byte) (int, string)

func BinaryDateTime added in v1.3.0

func BinaryDateTime(pos int, paramValues []byte) (int, string)

func BinaryDuration added in v1.3.0

func BinaryDuration(pos int, paramValues []byte, isNegative uint8) (int, string)

func BinaryDurationWithMS added in v1.3.0

func BinaryDurationWithMS(pos int, paramValues []byte,
	isNegative uint8) (int, string)

func BinaryTimestamp added in v1.3.0

func BinaryTimestamp(pos int, paramValues []byte) (int, string)

func BinaryTimestampWithTZ added in v1.3.0

func BinaryTimestampWithTZ(pos int, paramValues []byte) (int, string)

func CheckSqlPort added in v1.1.0

func CheckSqlPort(conn net.Conn) error

CheckSqlPort checks whether the SQL port is available.

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 GenerateAuthResp added in v1.3.0

func GenerateAuthResp(password, authPlugin string, salt []byte) ([]byte, error)

func GenerateSalt added in v1.3.0

func GenerateSalt(buf *[20]byte) error

GenerateSalt generates a random string using ASCII characters but avoid separator character. Ref https://github.com/mysql/mysql-server/blob/5.7/mysys_ssl/crypt_genhash_impl.cc#L435.

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 IsRetryableError added in v1.1.0

func IsRetryableError(err error) bool

func MakeChangeUser

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

MakeChangeUser creates the data of COM_CHANGE_USER.

func MakeCloseStmtRequest added in v1.3.0

func MakeCloseStmtRequest(stmtID uint32) []byte

func MakeEOFPacket added in v1.3.0

func MakeEOFPacket(status uint16) []byte

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

func MakeErrPacket added in v1.3.0

func MakeErrPacket(merr *gomysql.MyError) []byte

WriteErrPacket writes an Error packet.

func MakeExecuteStmtRequest added in v1.3.0

func MakeExecuteStmtRequest(stmtID uint32, args []any, newParamBound bool) ([]byte, error)

func MakeHandshakeResponse

func MakeHandshakeResponse(resp *HandshakeResp) []byte

func MakeInitialHandshake added in v1.3.0

func MakeInitialHandshake(capability Capability, salt [20]byte, authPlugin string, serverVersion string, connID uint64) []byte

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

func MakeOKPacket added in v1.3.0

func MakeOKPacket(status uint16, header Header) []byte

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

func MakePrepareStmtRequest added in v1.3.0

func MakePrepareStmtRequest(stmt string) []byte

func MakePrepareStmtResp added in v1.3.0

func MakePrepareStmtResp(stmtID uint32, paramNum int) []byte

MakePrepareStmtResp creates a prepared statement response. The packet is incomplete and it's only used for testing.

func MakeQueryPacket added in v1.3.0

func MakeQueryPacket(stmt string) []byte

func MakeShaCommand added in v1.3.0

func MakeShaCommand() []byte

func MakeSwitchRequest added in v1.3.0

func MakeSwitchRequest(authPlugin string, salt [20]byte) []byte

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

func MakeUserError added in v1.3.0

func MakeUserError(err error) []byte

WriteUserError writes an unknown error to the client.

func NewPacketIO

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

func ParseErrorPacket

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

ParseErrorPacket transforms an error packet into a MyError object.

func ParseExecuteStmtRequest added in v1.3.0

func ParseExecuteStmtRequest(data []byte, paramNum int, paramTypes []byte) (stmtID uint32, args []any, newParamTypes []byte, err error)

ParseExecuteStmtRequest parses ComStmtExecute request. NOTICE: the type of returned args may be wrong because it doesn't have the knowledge of real param types. E.g. []byte is returned as string, and int is returned as int32.

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 ParsePrepareStmtResp added in v1.3.0

func ParsePrepareStmtResp(resp []byte) (stmtID uint32, paramNum int)

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 ParseSSLRequestOrHandshakeResp added in v1.3.0

func ParseSSLRequestOrHandshakeResp(pkt []byte) bool

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 SkipLengthEncodedInt

func SkipLengthEncodedInt(b []byte) int

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

func Uint16ToBytes added in v1.3.0

func Uint16ToBytes(n uint16) []byte

func Uint32ToBytes added in v1.3.0

func Uint32ToBytes(n uint32) []byte

func Uint64ToBytes added in v1.3.0

func Uint64ToBytes(n uint64) []byte

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)

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 (*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 CommandFromString added in v1.3.0

func CommandFromString(str string) Command

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 InitialHandshake added in v1.3.0

type InitialHandshake struct {
	Salt          [20]byte
	ServerVersion string
	AuthPlugin    string
	ConnID        uint64
	Capability    Capability
}

func ParseInitialHandshake

func ParseInitialHandshake(data []byte) *InitialHandshake

ParseInitialHandshake parses the initial handshake received from the server.

type PacketIO

type PacketIO interface {
	ApplyOpts(opts ...PacketIOption)
	LocalAddr() net.Addr
	RemoteAddr() net.Addr
	ResetSequence()
	GetSequence() uint8
	ReadPacket() (data []byte, err error)
	WritePacket(data []byte, flush bool) (err error)
	ForwardUntil(dest PacketIO, isEnd func(firstByte byte, firstPktLen int) (end, needData bool),
		process func(response []byte) error) error
	InBytes() uint64
	OutBytes() uint64
	InPackets() uint64
	OutPackets() uint64
	Flush() error
	IsPeerActive() bool
	SetKeepalive(cfg config.KeepAlive) error
	LastKeepAlive() config.KeepAlive
	GracefulClose() error
	Close() error

	// proxy protocol
	EnableProxyClient(proxy *proxyprotocol.Proxy)
	EnableProxyServer()
	Proxy() *proxyprotocol.Proxy

	// tls
	ServerTLSHandshake(tlsConfig *tls.Config) (tls.ConnectionState, error)
	ClientTLSHandshake(tlsConfig *tls.Config) error
	TLSConnectionState() tls.ConnectionState

	// compression
	SetCompressionAlgorithm(algorithm CompressAlgorithm, zstdLevel int) error
}

type PacketIOption

type PacketIOption = func(*packetIO)

Jump to

Keyboard shortcuts

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